Jquery - 仅当存在新图像时才更改鼠标悬停图像

Jquery - Mouseover image change only if new image exists

我创建了一种简单的方法,可以通过将鼠标悬停在图片上来将我们的产品图片更改为次要图片。

当您将鼠标悬停在图像外时,它会切换回原始图像。

包含“-1.jpg”的文件为原图,“-3.jpg”为副图。所以代码将图像 src 从 -1 切换到 -3 足够简单。

我的问题是有些产品没有辅助图片,当将鼠标悬停在这些图片上时,当前会出现可见错误。

我正在尝试在我的代码中添加一种方法,以在更改图像之前检查次图像是否存在。如果不存在次映像,则不会发生任何事情。如果它确实存在,则将换入次图像。

附件是我的代码和测试jsfiddle

$(function() {
    $("[src*='-1.jpg']")
.mouseover(function() { 
            var src = $(this).attr("src").replace("-1.jpg", "-3.jpg");
            $(this).attr("src", src);
})
.mouseout(function() {
            var src = $(this).attr("src").replace("-3.jpg", "-1.jpg");
            $(this).attr("src", src);
        });
});

谢谢!

您将不得不尝试加载所有这些“次要图像”。

如果图像在临时变量中加载...它存在。因此,将 class 添加到 item,以便仅对那些已成功加载辅助图像的图像设置 hover 处理程序。

现在...由于所有这些 load 事件都需要一些时间,您必须使用 delegated event handler... 就像动态添加图像一样。

好的“副作用”是所有这些次要图像都将在浏览器中“预加载”...因此您的图像交换应该没有加载延迟。 一颗子弹打两个目标!

$(function() {

  // Check if -3.jpg exist for each image
  // If so, add a class
  $("[src*='-1.jpg']").each(function(index,item){
    let temp_img = $(`<img src="${item.src.replace("-1.jpg", "-3.jpg")}">`);
    temp_img.on("load", function(){
      $(item).addClass("hasSecondaryImage")
    })
  })
  

  // Delegated "hover" handler
  $(document).on("mouseover mouseleave", ".hasSecondaryImage", fonction(e){
    if (e.type === "mouseover"){
      var src = $(this).attr("src").replace("-1.jpg", "-3.jpg");
      $(this).attr("src", src);
    }
    if (e.type === "mouseleave"){
      var src = $(this).attr("src").replace("-3.jpg", "-1.jpg");
      $(this).attr("src", src);
    }
  })
  
})