2012-07-01 129 views
13

我正在實現文章元素的CSS3過渡效果,但事件監聽器transitionend只適用於純JavaScript,而不適用於jQuery。CSS3轉換事件監聽器與jQuery

見下面的例子:

// this works 
this.parentNode.addEventListener('transitionend', function() {alert("1"); }, true); 

// this does not work 
$(this).parent().addEventListener('transitionend', function() {alert("1"); }, true); 

有人可以解釋我什麼我做錯了嗎?

回答

19

在jQuery的你應該使用bind()on()方法:

$(this).parent().bind('transitionend', function() {alert("1"); }); 
+4

要獲得完整的兼容性,您還應該包含供應商前綴事件。參見http://blog.teamtreehouse.com/using-jquery-to-detect-when-css3-animations-and-transitions-end](http://blog.teamtreehouse.com/using-jquery-to-detect -when-css3-animations-and-transitions-end)以獲取詳細信息。 –

1

如果第一個真正的作品(我懷疑它,因爲它應該要求供應商名稱),那麼這應該工作太:

$(this).parent().on('transitionend', function() { 
    alert("1"); 
}); 
4

this.parentNode返回一個JavaScript對象。它有一個屬性.addEventListener $(this).parent()返回一個jQuery對象。它不會有一個屬性.addEventListener

試試這個,

$(this).parent().on('webkitTransitionEnd oTransitionEnd transitionend msTransitionEnd', function() { 
    alert("1"); 
}) 
23

還注意到,如果你是一個元素上運行多個過渡(如不透明度和寬度),你會得到多個transitionEnd回調。

如果您使用jQuery將事件綁定到div的轉換端,您可能需要考慮使用one()函數。

$(this).parent().one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function() { 
    // your code when the transition has finished 
}); 

這意味着代碼只會第一次觸發。所以,如果你在同一個元素上發生了四種不同的轉換,你的回調只會觸發一次。

+0

它是'one'還是'on'? – fboes

+1

使用'one()'確保您只捕獲一個事件。 – graygilmore

+0

你最好檢查一下e.currentTarget是否是正確的元素,因爲'transitionend'也會觸發其子對象的任何動畫。 – venimus