Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - CSS3过渡完成时回调(Callback when CSS3 transition finishes)

I'd like to fade out an element (transitioning its opacity to 0) and then when finished remove the element from the DOM.

(我想淡出一个元素(将其不透明度转换为0),然后在完成后从DOM中删除该元素。)

In jQuery this is straight forward since you can specify the "Remove" to happen after an animation completes.

(在jQuery中,这很简单,因为您可以指定动画完成后要执行的“删除”。)

But if I wish to animate using CSS3 transitions is there anyway to know when the transition/animation has completed?

(但是,如果我希望使用CSS3过渡进行动画处理,是否可以知道过渡/动画何时完成?)

  ask by C.J. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For transitions you can use the following to detect the end of a transition via jQuery:

(对于过渡,您可以使用以下内容通过jQuery检测过渡的结束:)

$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });

Mozilla has an excellent reference:

(Mozilla具有出色的参考:)

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition

(https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition)

For animations it's very similar:

(对于动画,它非常相似:)

$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });

Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.

(请注意,您可以将所有浏览器前缀的事件字符串同时传递到bind()方法中,以在所有支持该事件的浏览器上支持事件触发。)

Update:

(更新:)

Per the comment left by Duck: you use jQuery's .one() method to ensure the handler only fires once.

(根据Duck留下的评论:您使用jQuery的.one()方法来确保处理程序仅触发一次。)

For example:

(例如:)

$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });

$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });

Update 2:

(更新2:)

jQuery bind() method has been deprecated, and on() method is preferred as of jQuery 1.7 .

(jQuery bind()方法已被弃用,从jQuery 1.7首选on()方法。)

bind()

You can also use off() method on the callback function to ensure it will be fired only once.

(您还可以在回调函数上使用off()方法,以确保仅将其触发一次。)

Here is an example which is equivalent to using one() method:

(这是一个等效于使用one()方法的示例:)

$("#someSelector")
.on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
 function(e){
    // do something here
    $(this).off(e);
 });

References:

(参考文献:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...