悬停时jQuery交换图像,然后在悬停时将其替换为原始图像

时间:2015-04-09 17:56:44

标签: javascript jquery html5

我正在使用以下代码在孩子的父母悬停时交换图片src。如何将原始源保存在变量中并在悬停时将图像返回到其原始源?

      $("#parent span").hover(function(){
          var currentImage = $('img', this ).attr("src","images/orbs/yellowBar.png");
          $('img', this ).attr("src","images/yellowBar.png");


        },function(){

          $('img', this ).attr("src",currentImage);

      });

5 个答案:

答案 0 :(得分:3)

在您的函数之外定义currentImage

var currentImage;

$("#parent span").hover(function() {
    currentImage = $('img', this).attr("src", "images/orbs/yellowBar.png");
    $('img', this).attr("src", "images/yellowBar.png");
}, function() {
    $('img', this).attr("src", currentImage);
});

答案 1 :(得分:2)

至于我,更好的方法是创建两个具有不同背景图像的css类,并且在悬停时不要使用javascript / jquery进行图像切换。

的CSS:

.time-stamp-img {
    background:url('images/time_stamp_list_icon_play.png');
}
.time-stamp-img:hover {
    background:url('images/time_stamp_list_icon_hover.png');
}

HTML:

<div class="time-stamp-img"></div>

答案 2 :(得分:1)

我使用https://api.jquery.com/data/并在原始源的元素上设置数据点,然后在鼠标移出时检索它。

答案 3 :(得分:1)

在Dylan Watt建议的基础上,我使用.data()来避免全局变量。

这样的事情:

$("span").mouseenter(function () {
    var currentImage = $('img', this).attr("src");
    $('img', this).data("orig", currentImage)
    .attr("src", "http://placehold.it/350x150&text=hover");
}).mouseleave(function () {
    var original = $('img', this).data("orig");
    $('img', this).attr("src", original);
});

以下是您可以根据自己的需要调整的小提琴:

http://jsfiddle.net/djfe7rum/1/

答案 4 :(得分:0)

我建议使用mouseenter,mouseleave,因为:

var currentImage;
$("#parent span").mouseenter(function(){
    currentImage = $('img', this ).attr("src");
    $('img', this ).attr("src","images/yellowBar.png");
}).mouseleave(function(){
    $('img', this ).attr("src", currentImage);
});

如果这不起作用,请提供您的HTML代码。

相关问题