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

问题描述

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

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

包含“-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);
        });
});

谢谢!

解决方法

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

如果图像加载到一个临时变量中...它存在。因此,向 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);
    }
  })
  
})

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...