使用JavaScript检测CSS动画完成

One fact of web development life in 2014 that's been difficult for me to admit is that the traditional JavaScript toolkit is mostly dead.  For years we relied on them for almost everything but now that JavaScript and CSS has caught up with what we need, we can often avoid using JavaScript toolkits if we take the time to research new native capabilities.  One argument for sticking with toolkits that I often hear is that CSS animations don't provide callback abilities.

我很难承认2014年Web开发生涯的一个事实是,传统JavaScript工具包几乎已经死了。 多年来,我们几乎所有内容都依赖于它们,但是现在JavaScript和CSS赶上了我们的需求,如果我们花时间研究新的本机功能,我们通常可以避免使用JavaScript工具包。 我经常听到的坚持使用工具箱的一种说法是CSS动画不提供回调功能。

Wrong.  False.  Incorrect.  ¿Que?  JavaScript does provide us the ability to trigger functionality at the end of CSS animations and transitions. Here's how!

错误。 假。 不正确 ¿ JavaScript确实为我们提供了在CSS动画和过渡结束时触发功能的功能。 这是如何做!

JavaScript (The JavaScript)

The only reason this is a somewhat involved task at this point is the need to account for browser prefixes.  The transitionend event and animationend is what standardized browsers require but WebKit-based browsers still rely on prefixes so we have to determine the prefix for the event, then apply it:

此时,这是一项涉及到一定任务的唯一原因是需要考虑浏览器前缀。 标准化浏览器需要transitionend事件和animationend但是基于WebKit的浏览器仍然依赖前缀,因此我们必须确定事件的前缀,然后应用它:


/* From Modernizr */
function whichTransitionEvent(){
    var t;
    var el = document.createElement('fakeelement');
    var transitions = {
      'transition':'transitionend',
      'OTransition':'oTransitionEnd',
      'MozTransition':'transitionend',
      'WebkitTransition':'webkitTransitionEnd'
    }

    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

/* Listen for a transition! */
var transitionEvent = whichTransitionEvent();
transitionEvent && e.addEventListener(transitionEvent, function() {
	console.log('Transition complete!  This is the callback, no library needed!');
});

/*
	The "whichTransitionEvent" can be swapped for "animation" instead of "transition" texts, as can the usage :)
*/


Once the animation or transition ends, the callback fires.  No need for a big library to assign callbacks to animations anymore!

动画或过渡结束后,将触发回调。 不再需要大型库来为动画分配回调!

Imageine how much in JavaScript code you can save by avoiding a JavaScript library for this.  The duration, fill-mode, and delay can all be set via CSS, so your JavaScript stays lightweight.  Major win!

Imageine通过避免使用JavaScript库可以节省多少JavaScript代码。 持续时间,填充模式和延迟都可以通过CSS设置,因此您JavaScript保持轻量化。 大赢!

翻译自: https://davidwalsh.name/css-animation-callback

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值