悬停时随机更改图像

时间:2018-11-30 21:54:57

标签: javascript image random hover

我想在悬停时随机更改图像。悬停效果有效,但是当鼠标移出时图像不会变回原样。有什么想法吗?

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

1 个答案:

答案 0 :(得分:0)

控制台是否显示任何错误?我的猜测是var image = getRandomImage();的范围是在悬停时执行的回调函数,因此在鼠标移出时执行第二个函数时image是不确定的。

我的建议是将image的值保存在data- *属性中,以便在鼠标移出时读取,类似

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

额外提示:您应该保存$(this)的值,​​而不是每次都执行它,以避免重新创建jQuery对象。功能也可以链接起来。