javascript - 使用 Javascript 通过过渡更改悬停时的图像

标签 javascript html css

我正在使用 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>

最佳答案

CSS Transitions仅适用于 properties that can be expressed as numbers . 给定当前值、最终值以及从一个值到另一个值所需的时间,CSS 渲染引擎能够确定如何从一个属性值“过渡”到另一个属性值。图像 src 不是可以表示为数字的值,因此您的代码不会执行任何操作。

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

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

.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>

关于javascript - 使用 Javascript 通过过渡更改悬停时的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759080/

相关文章:

html - 超链接样式

ajax 调用后 JavaScript 不工作

javascript - 如何在 Jest 测试中比较(匿名)函数?

html - 如何使一个简单的 HTML 表格看起来像 "Handsontable"

javascript - 展开折叠问题

html - 单双列动态界面

javascript - 如何查看Google Drive API的文件和文件夹?

php - 如何创建不需要右键单击的 PDF 下载链接?

javascript - jquery 手机 : multiple data-filters showing

HTML5/CSS3 水平列表