2015-10-01 76 views
2

我想創建一個能夠消失後點擊它的元素。代碼顯然可以工作,但是,如果您嘗試多次單擊div,則會看到動畫重新啓動並執行多次。停止jQuery的動畫執行多次,當點擊

有沒有辦法讓它只播放一次,即使對它應用了多次點擊?

下面是我得到了什麼:

$(document).ready(
 
    function() { 
 
    $('#movingDiv').click(function() { 
 
     $(this).hide('slide', { 
 
     direction: 'right' 
 
     }, 1000); 
 
    }); 
 
    });
#movingDiv { 
 
    width: 50%; 
 
    height: 3em; 
 
    border: 3px solid red; 
 
    color: #000; 
 
    background-color: orange; 
 
    text-align: center; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script> 
 
<div id="movingDiv">Some content.</div>

+0

您的代碼段不運行 –

+0

@WillJenkins是的,我知道,我試圖理解爲什麼我可以把它在我的網站的工作,但不是在這裏...也許jQuery的版本.. – nowhere

+1

該片段不起作用,因爲你需要包括jQueryUI,或至少jQuery緩動庫 –

回答

1

使用 '解除綁定',以消除第一次點擊的點擊處理程序。

$(document).ready(
 
    function() { 
 
    $('#movingDiv').click(function() { 
 
     $(this).unbind('click').hide('slide', { 
 
     direction: 'right' 
 
     }, 1000); 
 
    }); 
 
    });
#movingDiv { 
 
    width: 50%; 
 
    height: 3em; 
 
    border: 3px solid red; 
 
    color: #000; 
 
    background-color: orange; 
 
    text-align: center; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
 
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js"></script> 
 
<div id="movingDiv">Some content.</div>

+0

感謝這一個似乎是最好的選擇。它甚至不會像stop()解決方案那樣閃爍。 – nowhere

+0

@nowhere你也可以使用.one(),它只會爲第一個事件附加一個事件https://api.jquery.com/one/(從1.1開始添加) – romuleald

2

需要清除每次點擊動畫隊列,而不是疊加起來的動畫。您可以使用stop()來實現這一目標:

$(document).ready(function(){ 
    $('#movingDiv').click(function() { 
     $(this).stop().hide('slide', { direction: 'right' }, 1000); 
    }); 
}); 

Working example

這使得當你點擊它

這是真實的動畫暫時停止。這是由於元素動畫的緩動效應。一種可能的解決方法是隻允許單擊該元素來隱藏它。

$('#movingDiv').one('click', function() { 
    $(this).hide('slide', { direction: 'right' }, 1000); 
}); 

Working example

+0

這會使動畫在您點擊時暫時停止 –

+0

這是由於緩動效應。你需要禁用緩動才能刪除它。 –

+0

我使用可能的解決方法更新了答案。顯然,使用'one()'意味着元素只能被點擊一次。我不確定這是否符合您的需求。 –