当使用jQuery悬停整个li时,如何更改li中的图像?

时间:2012-01-11 15:42:37

标签: jquery

我正在尝试使用这个简单的jquery脚本更改列表项(li img)中的锚点内的图像,但只有在鼠标悬停时才更改图像,但是如果将鼠标悬停在整个图像上我需要更改图像李。

$(".overview li a img").hover(
    function() { this.src = this.src.replace("_off", "_on"); },
    function() { this.src = this.src.replace("_on", "_off"); }
);

2 个答案:

答案 0 :(得分:2)

更改您的选择器以定位li,然后在处理程序中找到img子项并修改其来源:

$(".overview li").hover(
    function() {
        $(this).find("img")[0].src = $(this).find("img")[0].src.replace("_off", "_on");
    }, function() {
        $(this).find("img")[0].src = $(this).find("img")[0].src.replace("_on", "_off");
    });    
});

如果您愿意,可以将该行为压缩到.hover的单个函数参数中(虽然它的可读性稍差):

$(".overview li").hover(function () {
    var img = $(this).find("img")[0];
    img.src = (img.src.indexOf("_off") > -1) ? 
        img.src.replace("_off", "_on") : img.src.replace("_on", "_off");
});

答案 1 :(得分:1)

您是否考虑过使用CSS以及sprites来实现此效果?

这将为您提供您想要的内容,而无需在第一次加载图片时使用javascript并且不会轻微延迟悬停