javascript - 使用 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>
解决方案
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>
推荐阅读
- python - Kubernetes 中烧瓶迁移的最佳实践
- java - 如何将此嵌套三元 if-else 示例转换为 if-else 循环
- android - 没有上下文的 ResourcesCompat.getColor():错误 NotFoundException
- reactjs - 如何检查 Next-Js 组件状态?
- python - QtWidgets.QWidget() 返回什么小部件?
- c# - ASP.NET MVC 在单个 HTTP 发布请求中更新主从记录
- python - OLS 回归结果显示 R 平方和调整后的 R 平方分别为 0.091 和 0.074。我的模型有那么差吗?
- r - 特定条件下的颜色 geom_rect
- c# - Datagrid 在 ASP NET C# 中显示最后不需要的空白列
- python-sphinx - 如何调整手册页宽度