我需要能够在悬停时淡入初始图像上方的第二个图像。我需要确保第二张图片最初不可见,直到它淡入。另一个重要注意事项是任何一张图片都不应完全淡出。我尝试了几种方法,例如使用 1 个图像、2 个图像、jquery animate 和 css 转换。
我读到可以使用 jquery 为属性的变化设置动画?如果这是真的,我如何使用 jquery 为 img 中“src”的变化设置动画?
$(".image").mouseenter(function() {
var img = $(this);
var newSrc = img.attr("data-hover-src");
img.attr("src",newSrc);
img.fadeTo('slow', 0.8, function() {
img.attr("src", newSrc);
});
img.fadeTo('slow', 1);
}).mouseleave(function() {
var img = $(this);
var newSrc = img.attr("data-regular-src");
img.fadeTo('slow', 0.8, function() {
img.attr("src", newSrc);
});
img.fadeTo('slow', 1);
});
这是我目前正在使用的。这是我得到的最接近的。但是您可以看到图像发生了不可取的变化。
最佳答案
使用带有背景图片的单个 html 元素
HTML - 没有比这更简单的了
<div id="imgHolder"></div>
CSS
#imgHolder {
width: 200px;
height: 200px;
display: block;
position: relative;
}
/*Initial image*/
#imgHolder::before {
content:"";
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
background-image:url(http://placehold.it/200x200);
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
z-index:10;
}
#imgHolder:hover::before {
opacity:0;
}
#imgHolder::after {
content:"";
background: url(http://placehold.it/200x200/FF0000);
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
或者如果您想使用图片标签...
直接窃取自:http://css3.bradshawenterprises.com/cfimg/
HTML
<div id="cf">
<img class="bottom" src="pathetoImg1.jpg" />
<img class="top" src="pathetoImg2.jpg" />
</div>
CSS
#cf {
position:relative;
height:281px;
width:450px;
margin:0 auto;
}
#cf img {
position:absolute;
left:0;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
#cf img.top:hover {
opacity:0;
}
链接中还有许多其他示例可供使用,但这将帮助您入门。
最终不透明度
您提到过您不希望初始图像完全消失。为此,请将 opacity:0
更改为 opacity:0.5
或类似内容。您需要对该值进行试验以获得所需的结果。
Demo with final opacity of 0.8
动态图像大小
我认为如果只使用 CSS,您将无法使用 双图像 版本。 HTML 是一样的。
CSS
#cf {
position:relative;
}
#cf img {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
#cf img.bottom {
z-index:-1;
opacity:0;
position:absolute;
left:0;
}
#cf:hover img.top {
opacity:0.8;
}
#cf:hover img.bottom {
display:block;
opacity:1;
}
关于javascript - 使用 css 或 jquery 将一张图片淡入另一张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793139/