简体   繁体   English

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

[英]jQuery swap image on hover, then replace it with original on hover off

I am using the following code to swap an image src out on hover of the child's parent. 我正在使用以下代码在孩子的父母悬停时交换图像src。 How can I save the original source in a variable and on hover off return the image to its original source? 如何将原始源保存在变量中并在悬停时将图像恢复为原始源?

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

      });

Define currentImage outside of your function: 在函数之外定义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);
});

As for me, the better way is to create two css classes with different background image and don't use javascript/jquery for image switch on hover at all. 至于我,更好的方法是创建两个具有不同背景图像的css类,并且根本不使用javascript / jquery进行图像切换。

css: 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: HTML:

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

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

Building on Dylan Watt's suggestion I'd use .data() to avoid a global variable. 基于Dylan Watt的建议,我将使用.data()来避免全局变量。

So something like this: 所以像这样:

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

And here's the fiddle that's from that you can adapt for your use: 以下是您可以根据自己的需要调整的小提琴:

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

I would suggest using mouseenter, mouseleave, as such: 我建议使用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);
});

If this doesn't work, please provide your HTML code. 如果这不起作用,请提供您的HTML代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM