使用css或jquery将一个图像淡入另一个图像

我需要能够在hover时淡入初始图像上方的第二张图像。 我需要确保第二张图像最初不可见,直到它渐渐消失。另一个重要的注意事项是, 这些图像都不应该在任何时候完全淡出 。 我尝试了几种方法,例如使用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 – 并不比这更简单

 

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

 

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 opacity:0.5或类似的东西。 您需要尝试使用该值来获得所需的结果。

最终不透明度为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; } 

演示