CSS3 过渡完成时的回调 [英] Callback when CSS3 transition finishes

查看:35
本文介绍了CSS3 过渡完成时的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在 jQuery 中,这很简单,因为您可以指定在动画完成后发生的删除".但是,如果我想使用 CSS3 过渡来制作动画,无论如何要知道过渡/动画何时完成?

In jQuery this is straight forward since you can specify the "Remove" to happen after an animation completes. But if I wish to animate using CSS3 transitions is there anyway to know when the transition/animation has completed?

推荐答案

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

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

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

Mozilla 有一个很好的参考:

Mozilla has an excellent reference:

https://developer.mozilla.org/en-US/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(){ ... });

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

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.

更新:

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

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

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

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

更新 2:

jQuery bind() 方法已被弃用,on() 方法从 jQuery 1.7 开始是首选方法.bind()

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

您还可以在回调函数上使用 off() 方法来确保它只会被触发一次.这是一个等效于使用 one() 方法的示例:

You can also use off() method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using one() method:

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

参考文献:

.one()

这篇关于CSS3 过渡完成时的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆