Jos*_*osh 3 html javascript css jquery image
我需要能够在悬停时在初始图像上方淡入第二张图像。我需要确保第二个图像在淡入之前最初不可见。另一个重要的注意事项是任何时候都不应完全淡出图像。我尝试了几种方法,例如使用 1 张图像、2 张图像、jquery 动画和 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);
});
Run Code Online (Sandbox Code Playgroud)
这是我目前正在使用的。这是我得到的最接近的。但是您可以看到图像发生了不理想的变化。
使用带有背景图像的单个 html 元素
HTML - 没有比这更简单的了
<div id="imgHolder"></div>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用图像标签...
直接窃取:http : //css3.bradshawenterprises.com/cfimg/
HTML
<div id="cf">
<img class="bottom" src="pathetoImg1.jpg" />
<img class="top" src="pathetoImg2.jpg" />
</div>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
链接中还有许多其他示例可供使用,但这将帮助您入门。
最终不透明度
您已经提到您不希望初始图像完全消失。要做到这一点的变化opacity:0来opacity:0.5或类似的东西。您需要对该值进行试验以获得所需的结果。
动态图像尺寸
我认为如果只使用 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5439 次 |
| 最近记录: |