Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JQuery:悬停时动态图像替换?_Jquery - Fatal编程技术网

JQuery:悬停时动态图像替换?

JQuery:悬停时动态图像替换?,jquery,Jquery,我想要一个接受img元素的Jquery函数,当它悬停时,它会像这样替换img:myimage.png替换为myimage2.png 这是我想到的,但它不起作用: $("#menu img").hover(function(){ var split = $(this).attr("src").split(".png"); $(this).attr("src", split[0]+"2.png"); }, function(){

我想要一个接受img元素的Jquery函数,当它悬停时,它会像这样替换img:myimage.png替换为myimage2.png

这是我想到的,但它不起作用:

        $("#menu img").hover(function(){
        var split = $(this).attr("src").split(".png");
        $(this).attr("src", split[0]+"2.png");
    }, function(){
        var split = $(this).attr("src").split(".png");
        $(this).attr("src", split[0]+".png");
    });

我相信老兵们会想出一个更好的方法,所以请。

希望这有帮助,如果你有任何问题,请告诉我

jsFiddle()


var split=新数组();
拆分[0]=”http://www.google.com/logos/2012/sundback12-hp.jpg";
拆分[1]=”http://www.google.com/logos/2012/sovereignty12_hp.jpg";
$(文档).ready(函数()
{
$(“.button”).hover(函数()
{
$(this.attr(“src”,split[1]);
},
函数()
{
$(this.attr(“src”,split[0]);
});
});
​

您的第二个函数根本不会更改
src
属性,因为您所做的只是删除“.png”位,然后重新添加它。您还需要删除“2”。我想您可以将
split('.png')
更改为
split('2.png')

但在大多数情况下,CSS是一个更好的解决方案。除非您确实想要显示图像(如在图库中),否则您可以在其他元素上设置背景图像,并在悬停时交换它们。更好的是,使用图像精灵将HTTP请求降至最低:

#menu a {
    background: url(menu.png) no-repeat; /* menu.png contains ALL the images used in the menu */
    display: block;
    width: 80px;
    height: 20px;
    text-indent: -1000000px; /* Remove text */
}

#menu a:hover {
    background-position: left -20px;
}
#menu a {
    background: url(menu.png) no-repeat; /* menu.png contains ALL the images used in the menu */
    display: block;
    width: 80px;
    height: 20px;
    text-indent: -1000000px; /* Remove text */
}

#menu a:hover {
    background-position: left -20px;
}