在悬停时更改img src时如何添加过渡? [英] How to add transition when changing img src on hover?

查看:370
本文介绍了在悬停时更改img src时如何添加过渡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我使用javascript悬停原始图片时,我正在尝试添加其他图片.我的语法与此类似,效果很好.

So I'm trying to add a different image when the original image is hovered over using javascript. The syntax I have is similar to this, which works great.

function imgHover() {
    projectImage.src = '../img/img1.png';
}
function imgHover2() {
    projectImage.src = '../img/img2.png';
}

projectImage.addEventListener('mouseover', imgHover); 
projectImage.addEventListener('mouseleave', imgHover2); 

现在,我正在尝试寻找一种方法,以使图像从一个过渡到另一个(最有可能使用不透明度.)有关如何执行此操作的任何建议?我不知道.

Now I'm trying to find a way to make the image transition from one to the other (most likely using opacity.) Any suggestions on how to do this? I can't figure it out.

推荐答案

您不能创建仅更改图像的src标签的过渡效果.

You can't create a transition effect changing just the src tag of an image.

一种方法是创建两个图像,将它们彼此绝对放在顶部,而顶部图像的不透明度为0.

One way of doing this is to create two image that is positioned absolute on top of each other with the top one having an opacity of 0.

如果您需要动态更改悬停图片,仍然可以通过javascript进行.

If you need to change the hover image dynamically, you can still do that through javascript.

.image-wrapper {
  position: relative;
}
.image-hover {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 1s ease-out;
}
.image-hover:hover {
  opacity: 1;
}

<div class="image-wrapper">
  <img src="http://via.placeholder.com/350x150?text=normal" class="image" alt="normal" />
  <img src="http://via.placeholder.com/350x150?text=hover" class="image-hover" alt="hover" />
</div>

这篇关于在悬停时更改img src时如何添加过渡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆