Javascript CSS 过渡回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2087510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:43:16  来源:igfitidea点击:

Callback on CSS transition

javascriptcsscss-transitions

提问by Pompair

Is it possible to get a notification (like callback) when a CSS transition has been completed?

当 CSS 转换完成时,是否可以收到通知(如回调)?

采纳答案by Doug Neiner

I know that Safari implements a webkitTransitionEndcallback that you can attach directly to the element with the transition.

我知道 Safari 实现了一个webkitTransitionEnd回调,您可以将它直接附加到带有过渡的元素。

Their example (reformatted to multiple lines):

他们的例子(重新格式化为多行):

box.addEventListener( 
     'webkitTransitionEnd', 
     function( event ) { 
         alert( "Finished transition!" ); 
     }, false );

回答by Mark Rhodes

Yes, if such things are supported by the browser, then an event is triggered when the transition completes. The actual event however, differs between browsers:

是的,如果浏览器支持这样的事情,那么当转换完成时会触发一个事件。然而,实际事件因浏览器而异:

  • Webkit browsers (Chrome, Safari) use webkitTransitionEnd
  • Firefox uses transitionend
  • IE9+ uses msTransitionEnd
  • Opera uses oTransitionEnd
  • Webkit 浏览器(Chrome、Safari)使用 webkitTransitionEnd
  • 火狐使用 transitionend
  • IE9+ 用途 msTransitionEnd
  • 歌剧用途 oTransitionEnd

However you should be aware that webkitTransitionEnddoesn't always fire! This has caught me out a number of times, and seems to occur if the animation would have no effect on the element. To get around this, it makes sense to use a timeout to fire the event handler in the case that it's not been triggered as expected. A blog post about this problem is available here: http://www.cuppadev.co.uk/the-trouble-with-css-transitions/<-- 500 Internal Server Error

但是你应该知道它webkitTransitionEnd并不总是会触发!这让我很不爽,而且似乎在动画对元素没有影响的情况下会发生。为了解决这个问题,在没有按预期触发的情况下使用超时来触发事件处理程序是有意义的。有关此问题的博客文章可在此处找到:http: //www.cuppadev.co.uk/the-trouble-with-css-transitions/ <-- 500 Internal Server Error

With this in mind, I tend to use this event in a chunk of code that looks a bit like this:

考虑到这一点,我倾向于在看起来有点像这样的代码块中使用这个事件:

var transitionEndEventName = "XXX"; //figure out, e.g. "webkitTransitionEnd".. 
var elemToAnimate = ... //the thing you want to animate..
var done = false;
var transitionEnded = function(){
     done = true;
     //do your transition finished stuff..
     elemToAnimate.removeEventListener(transitionEndEventName,
                                        transitionEnded, false);
};
elemToAnimate.addEventListener(transitionEndEventName,
                                transitionEnded, false);

//animation triggering code here..

//ensure tidy up if event doesn't fire..
setTimeout(function(){
    if(!done){
        console.log("timeout needed to call transition ended..");
        transitionEnded();
    }
}, XXX); //note: XXX should be the time required for the
        //animation to complete plus a grace period (e.g. 10ms) 

Note: to get the transition event end name you can use the method posted as the answer in: How do I normalize CSS3 Transition functions across browsers?.

注意:要获取转换事件结束名称,您可以使用作为答案发布的方法: 如何规范跨浏览器的 CSS3 转换功能?.

Note: this question is also related to: - CSS3 transition events

注意:这个问题也与:- CSS3 过渡事件有关

回答by Tom

I am using the following code, is much simpler than trying to detect which specific end event a browser uses.

我正在使用以下代码,这比尝试检测浏览器使用的特定结束事件要简单得多。

$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', 
function() {
 //do something
});


Alternatively if you use bootstrap then you can simply do

或者,如果您使用引导程序,那么您可以简单地执行

$(".myClass").one($.support.transition.end,
function() {
 //do something
});

This is becuase they include the following in bootstrap.js

这是因为它们在 bootstrap.js 中包含以下内容

+function ($) {
  'use strict';

  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      'WebkitTransition' : 'webkitTransitionEnd',
      'MozTransition'    : 'transitionend',
      'OTransition'      : 'oTransitionEnd otransitionend',
      'transition'       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }

    return false // explicit for ie8 (  ._.)
  }

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false, $el = this
    $(this).one($.support.transition.end, function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

  $(function () {
    $.support.transition = transitionEnd()
  })

}(jQuery);

回答by Brian

The jQuery.transit plugin, a plugin for CSS3 transformations and transitions, can call your CSS animations from script and give you a callback.

jQuery.transit插件,对CSS3转换和过渡的一个插件,可以从脚本中调用你的CSS动画,并给您一个回调。

回答by Yehuda Schwartz

This can easily be achieved with the transitionendEvent see documentation hereA simple example:

这可以通过transitionend事件轻松实现,请参见此处的文档一个简单的示例:

document.getElementById("button").addEventListener("transitionend", myEndFunction);

function myEndFunction() {
 this.innerHTML = "Transition event ended";
}
#button {transition: top 2s; position: relative; top: 0;}
<button id="button" onclick="this.style.top = '55px';">Click me to start animation</button>