簡體   English   中英

.mouseleave()和.mouseenter()的問題

[英]Issue with .mouseleave() and .mouseenter()

我使用.mouseenter()和.mouseleave()將動畫制作到我的按鈕上。問題是,當我在按鈕上多次移動光標時,它會不斷重復動畫。對於.mouseenter(),我希望它完成動畫一旦光標一直懸停在動畫上,直到動畫時間結束,並且動畫在動畫完成前離開按鈕,動畫應停止。對於.mouseleave(),如果光標在動畫完成前將鼠標懸停在動畫上,動畫應停止。

 $(document).ready(function(){ $('#button').mouseenter(function(){ $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100); }); $('#button').mouseleave(function(){ $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100); }); }); 
 #button{ width:100px; height:50px; background-color:red; } 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script> <div id="button"></div> 

您可以使用標志進入和離開。 然后檢查適當的標志,並在發生enter / leave事件時完成當前動畫,如下所示:

$(document).ready(function () {
    var isEntering = false, // Create flags
        isLeaving = false;
    $('#button').mouseenter(function () {
        isEntering = true; // Set enter flag
        if (isLeaving) {   // Check, if leaving is on process
            $(this).finish(); // If leaving, finish it
            isLeaving = false; // Reset leaving flag
        }
        $(this).animate({
            backgroundColor: '#ffce00',
            width: '+=1em'
        }, 100);
    });
    $('#button').mouseleave(function () {
        isLeaving = true; // Set leave flag
        if (isEntering) { // Check if entering is on process
            $(this).finish(); // If it is, finish it
            isEntering = false; // Reset enter flag
        }
        $(this).animate({
            backgroundColor: '#1e7989',
            width: '-=1em'
        }, 100);
    });
});

jsFiddle上的現場演示

嘗試添加.stop() ,它將停止動畫的排隊。

$(document).ready(function(){
    $('#button').mouseenter(function(){
        $(this).stop().animate({backgroundColor:'#ffce00',width:'+=1em'},100);
    });
    $('#button').mouseleave(function(){
        $(this).stop().animate({backgroundColor:'#1e7989',width:'-=1em'},100);
    });
});

問候,加多斯

如果只希望它運行一次,則可以在事件觸發后解除綁定:

$(document).ready(function(){
    $('#button').mouseenter(function(){
        $(this).animate({backgroundColor:'#ffce00',width:'+=1em'},100);
        $(this).unbind('mouseenter');
    });
    $('#button').mouseleave(function(){
        $(this).animate({backgroundColor:'#1e7989',width:'-=1em'},100);
        $(this).unbind('mouseleave');
    });   
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM