简体   繁体   中英

Change image randomly when hover

i want to change an image randomly when hovering. The Hover effect is working but when the mouse moves out the image does not change back. Any ideas?

var arr = ["020", "053", "306", "035", "930"];

function getRandomImage() {
  var index = Math.floor(Math.random() * arr.length);

  return arr[index];

}

$(function(){
$(".size-woocommerce_thumbnail").hover(function(){
    var image = getRandomImage();
    $(this).attr("srcset", function(index, attr){
        return attr.replace("070", image);
    });
    $(this).attr("src", function(index, attr){
        return attr.replace("070", image);
    });
}, function(){
    $(this).attr("srcset", function(index, attr){
        return attr.replace(image, "070");
    });
    $(this).attr("src", function(index, attr){
        return attr.replace(image, "070");
    });
});
});

Does the console show any error? My guess is that the scope of var image = getRandomImage(); is the callback function executed on hover, so image is undefined when the second function is executed on mouseout.

My suggestion is to save the value of image in a data-* attribute to read on mouseout, something like

$(".size-woocommerce_thumbnail").hover(function(){
  var $this = $(this);
  var image = getRandomImage();
  $this.attr("srcset", function(index, attr){
    return attr.replace("070", image);
  });
  $this.attr("src", function(index, attr){
    return attr.replace("070", image);
  });
  $this.data('image', image);
}, function(){
  var $this = $(this);
  var image = $this.data('image');
  $this.attr("srcset", function(index, attr){
      return attr.replace(image, "070");
  });
  $this.attr("src", function(index, attr){
      return attr.replace(image, "070");
  });
});

Extra tip: you should save the value of $(this) instead of executing it every time, to avoid recreating the jQuery object. Functions could be chained as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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