首页 > 解决方案 > 使用 Javascript 通过过渡更改悬停图像

问题描述

我正在使用 JavaScript 在悬停时更改图像。但是,使用此 css 和代码,两个图像之间的转换无法按预期工作

function changeImageOnHoverOver() {
  var changeImg = document.getElementById('change-img');
  changeImg.setAttribute("src", "https://demotheme.site/prestashop/at_kola_demo/51-large_default/mug-the-best-is-yet-to-come.jpg");
}

function changeImageOnHoverOut() {
  var changeImg = document.getElementById('change-img');
  changeImg.setAttribute("src", "https://demotheme.site/prestashop/at_kola_demo/36-home_default/the-best-is-yet-to-come-framed-poster.jpg");
}
a img {
  border-radius: 8px;
  transition: all 0.4s;
}
<a href="">
  <img src="https://demotheme.site/prestashop/at_kola_demo/36-home_default/the-best-is-yet-to-come-framed-poster.jpg" onmouseover="changeImageOnHoverOver()" onmouseout="changeImageOnHoverOut()" alt="" id="change-img" width="300">
</a>

标签: javascripthtmlcss

解决方案


CSS 过渡仅适用于可以表示为数字的属性给定当前值、最终值和从一个到另一个所需的时间,CSS 渲染引擎能够确定如何从一个属性值“转换”到另一个属性值。图像src不是可以表示为数字的值,因此您的代码不会做任何事情。

相反,使用类似的属性opacity来创建交叉淡入淡出效果。不透明度取值从 0 到 1,因此它适用于过渡。

此外,如果您希望在鼠标悬停和鼠标移出时发生效果,则不需要 JavaScript,只需使用 CSS:hover伪类仅在元素被悬停时应用样式。如果不是,则删除样式。

.container img {
  height:200px;
  /* Positioning the images absolute allows them to stack on top of each other */
  position:absolute;
  left:0;
  border-radius: 8px;
  transition: opacity 0.4s ease-in-out;
}

/* Change the opacity when the top image is hovered, which
   will reveal the bottom image */
.container img.top:hover {
  opacity:0;
}
<div class="container">
  <img class="bottom" 
    src="https://demotheme.site/prestashop/at_kola_demo/36-home_default/the-best-is-yet-to-come-framed-poster.jpg">
  <img class="top" 
   src="https://demotheme.site/prestashop/at_kola_demo/51-large_default/mug-the-best-is-yet-to-come.jpg">
</div>


推荐阅读