我的页面有完整的代码,因此您可以自己查看:
<html>
<head>
</head>
<body>
<link rel="Stylesheet" type="text/css" href="style.css" />
<style type = "text/css">
#img1 {
opacity: 1;
display: block;
position: fixed;
top: 0;
left: 0;
}
#img2 {
opacity: 1;
display: block;
position: fixed;
top: 0;
left: 0;
}
#cont {
position: fixed;
top: 0;
left: 0;
width: 880px;
height: 360px;
border: 5px;
border-style: solid;
background-color: red;
z-index: 100;
opacity: 0.9;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type = "text/javascript">
$(document).ready(function()
{
var check = 0;
var ended = 1;
var ended2 = 1;
$("#img2").mouseenter(function()
{
if (check == 0 && ended == 1)
{
ended = 0;
$("#img2").fadeOut(500, function()
{
$("#img2").css({"z-index":"2"});
$("#img1").css({"z-index":"3"});
ended = 1;
}).fadeIn(1);
check = 1;
}
});
$("#cont").mouseleave(function()
{
check = 0;
if (ended2 == 1)
{
ended2 = 0;
$("#img1").fadeOut(500, function()
{
$("#img2").css({"z-index":"4"});
$("#img1").css({"z-index":"1"});
ended2 = 1;
}).fadeIn(1);
}
});
});
</script>
<div id = "cont">
<img src = "http://s16.postimg.org/egzrkpa1h/img1.jpg" id = "img1">
<img src = "http://s23.postimg.org/kzurc5h63/img2.jpg" id = "img2">
</div>
</body>
</html>
代码的工作原理很简单:当鼠标聚焦在图片上时,它会“改变颜色”,当离开红色 div 时 - 它会返回到之前的状态。 问题是:当我在脚本结束之前(开始动画 500 毫秒之前)将鼠标移动到图片区域时,两张图片都会消失一会儿。我添加了变量结束和结束2的条件 - 我不知道为什么它们不起作用..我花了整夜寻找错误,但没有找到任何东西,所以请帮助我:)
最佳答案
为了回答你的问题,两张图片同时变得透明,所以你会看到背景。尝试仅对顶部图像应用透明度,然后您不必使用 z-index 或其他任何内容更改它们的顺序,但是...
你不需要 JavaScript 来做到这一点。通过 css 添加悬停状态,您将得到相同的结果。尝试删除所有 javascript,然后将其添加到您的 css 中:
#img2:hover {opacity:0;}
#img2 {transition: opacity 0.5s;}
如果您确实想使用 jQuery,请尝试悬停,其中第一个参数是“鼠标悬停时”,第二个参数是“鼠标离开时”:
$(document).ready(function(){
var topImage = $("#img2");
topImage.hover(
function(){
topImage.stop().animate({opacity:0});
},
function(){
topImage.stop().animate({opacity:1});
}
);
});
关于jquery - 当我改变其属性太快时图像消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18072601/