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保持轻量化。 大赢!