我正试图找到一种方法来在鼠标悬停在黑色区域时停止fadeIn / fadeOut动画:
$(function(){
$('.text').mouseenter(function(){
$(this).stop(true,true).fadeOut();
}).mouseleave(function(){
$(this).stop(true,true).fadeIn();
});
});
<div id="container">
<div class="text">s</div>
</div>
#container{width:600px; height:100%; position:relative;}
.text{position:absolute; left:0; top:0; width:200px;
height:800px; background:#000000;}
每次鼠标移动到该区域内时,该功能都会循环播放。我怎么能避免这个?
答案 0 :(得分:4)
很难确切知道这将用于什么(意图是什么),但我会尝试使用jQuery hover()函数并使用fadeTo()将元素淡化为0不透明度。
$(".text").hover(
function () {
$(this).stop(true, true).fadeTo('slow', 0)
},
function () {
$(this).stop(true, true).fadeTo('slow', 1)
}
);
但根据您的使用情况,这可能不正确。
示例: http://jsfiddle.net/AeZP4/3/
修改:根据maxfieldens建议添加了stop():http://jsfiddle.net/AeZP4/6/
答案 1 :(得分:1)
原始代码的真正问题是fadeOut和mouseleave在同一元素上的组合。如果在鼠标悬停在div上时fadeOut,则此元素将消失,因此将触发mouseleave事件。 mouseleave处理程序进行fadeIn调用,div再次可见,触发mouseenter事件,我们从头开始循环。这是一个经典的无限循环:http://jsfiddle.net/AeZP4/1/
fadeTo函数运行良好,因为在这种情况下div是透明的但没有消失(显示:无)。