开发者

jQuery: using hover to roll-over multiple images at once

I have a small problem, but I'm a bit stumped.

I am using the following code to do rollovers on my webpage

$("#mylink1 img").hover(
 function()
 {
  this.src = this.src.replace("_off","_on");
 },
 function()
 {
  thi开发者_Python百科s.src = this.src.replace("_on","_off");
 }
);

This works great for individual images, but I would like to roll over one of them and have the the other one change as well.

<a id="mylink1" href="about.cfm"><img src="images/Home_top_navs/aboutus_manage_off.gif" /></a>

<a id="mylink1" href="about.cfm"><img src="images/Home_top_navs/aboutus_nav2_off.gif" /></a>

Any help would be appreciated! Thank you!


Don't use id, use class because id is unique.

<a class="mylink1" href="about.cfm"><img src="images/Home_top_navs/aboutus_manage_off.gif"  /></a>

<a class="mylink1" href="about.cfm"><img src="images/Home_top_navs/aboutus_nav2_off.gif" /></a>

then:

$(".mylink1 img").hover(


Change id to string @corroded suggested. IDs should be unique within a page.

As for changing multiple images when hovering over a single image, you have to modify the hover over and out functions. Currently, they are only changing the src attribute of the image currently hovered over. Instead, inside both the functions, you have to loop through each image and change the src attribute. Something like:

$("#mylink1 img").hover(
    function() {
        $(".mylink1 img").each(function() {
            this.src = this.src.replace("_off","_on");
        });
    },
    function() {
        $(".mylink1 img").each(function() {
            this.src = this.src.replace("_on","_off");
        });
    }
);

You can avoid the duplication with some currying:

(function() {
    var images = $(".mylink1 img");

    function imageSwapper(imgs, from, to) {
        return function() {
            imgs.each(function() {
                this.src = this.src.replace(from, to);
            });
        };
    }

    $(images).hover(
        imageSwapper(images, "_off", "_on"),
        imageSwapper(images, "_on", "_off")
    );
})();​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜