[英]how to prevent a event listener function to be triggered several times at the same time
[英]How to prevent JavaScript from applying the mouseover event several times
我在測試mouseover
事件時注意到一個問題。 在下面的示例中,有一個圖像,當您將其懸停時,它會變大,當鼠標移出時,它會恢復到正常大小,但是當您將鼠標快速移過它多次時,它會越來越大幾次,就像它已經記住了鼠標的每一次通過並不斷播放動畫一樣。
這是一個實時示例: 在此處繼續快速移動鼠標,將鼠標移到和移出圖像之后,將鼠標移開,您將看到。
讓我向您介紹CSS3,這使jQuery變得過時了: Demo
HTML:
<img src="......./Smiley.png" alt="smile" id="imgSmile" />
CSS:
#imgSmile {
width:200px;
transition:width 0.4s ease;
}
#imgSmile:hover {
width:250px;
}
JS:沒有!
您可以在制作動畫的同時添加一個類,並在完成動畫后將其刪除,並且僅當該類未應用於元素時才應用新的動畫。 例:
$(document).ready(function(){
$('#imgSmile').width(200);
$('#imgSmile').mouseover(function()
{
if(!$(this).hasClass('animating')){
$(this).css("cursor","pointer");
$(this).addClass('animating');
$(this).animate({width: "250px"}, 'slow',function(){
$(this).removeClass('animating');
});
}
});
$('#imgSmile').mouseout(function()
{
$(this).animate({width: "200px"}, 'slow');
});
});
演示: http : //jsfiddle.net/bR5cm/3/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.