jQuery:使用悬停一次翻转多个图像

时间:2010-05-28 07:00:45

标签: jquery rollover

我有一个小问题,但我有点难过。

我使用以下代码在我的网页上进行翻转

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

这适用于单个图像,但我想翻过其中一个并让另一个也改变。

<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>

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:2)

不要使用id,因为id是唯一的,所以请使用class。

<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>

然后:

$(".mylink1 img").hover(

答案 1 :(得分:1)

将id改为字符串@corroded建议。 ID在页面中应该是唯一的。

对于将鼠标悬停在单个图像上时更改多个图像,您必须修改悬停过度和结束功能。目前,它们只是更改当前悬停的图像的src属性。相反,在这两个函数中,您必须遍历每个图像并更改src属性。类似的东西:

$("#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");
        });
    }
);

你可以通过一些讨论来避免重复:

(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")
    );
})();​