Skip to content

Instantly share code, notes, and snippets.

@bennyzhao
Created September 19, 2013 00:50
Show Gist options
  • Save bennyzhao/6617816 to your computer and use it in GitHub Desktop.
Save bennyzhao/6617816 to your computer and use it in GitHub Desktop.
Capture CSS3 Animation Events in JavaScript from:https://gist.github.com/kewah/4493678
#anim.enable
{
-webkit-animation: flash 1s ease 3;
-moz-animation: flash 1s ease 3;
-ms-animation: flash 1s ease 3;
-o-animation: flash 1s ease 3;
animation: flash 1s ease 3;
}
/* animation */
@-webkit-keyframes flash {
50% { opacity: 0; }
}
@-moz-keyframes flash {
50% { opacity: 0; }
}
@-ms-keyframes flash {
50% { opacity: 0; }
}
@-o-keyframes flash {
50% { opacity: 0; }
}
@keyframes flash {
50% { opacity: 0; }
}
var anim = document.getElementById("anim");
// anim.addEventListener("animationstart", AnimationListener, false);
// animationstart事件在动画第一次开始时触发
// anim.addEventListener("animationiteration", AnimationListener, false);
// animationiteration事件在每次动画迭代的一开始触发(但是不包括第一次也就是上面的start)
// anim.addEventListener("animationend", AnimationListener, false);
// animationend事件在整个动画结束时触发
// 创建一个兼容的获取事件的方法
var CSSAnimation = (function(window, document, undefined) {
'use strict';
function camelCaseEventTypes(prefix) {
prefix = prefix || '';
return {
start: prefix + 'AnimationStart',
end: prefix + 'AnimationEnd',
iteration: prefix + 'AnimationIteration'
};
}
function lowerCaseEventTypes(prefix) {
prefix = prefix || '';
return {
start: prefix + 'animationstart',
end: prefix + 'animationend',
iteration: prefix + 'animationiteration'
};
}
/**
* @return {Object} Animation Event types {start, end, iteration}
*/
function getEventTypes() {
var prefixes = ['webkit', 'Moz', 'O', ''];
var style = document.documentElement.style;
if(style.animationName !== undefined) {
return lowerCaseEventTypes();
}
for(var i = 0, len = prefixes.length, prefix; i < len; i++) {
prefix = prefixes[i];
if(style[prefix + 'AnimationName'] !== undefined) {
if(i === 0) {
return camelCaseEventTypes(prefix.toLowerCase());
} else if(i === 1) {
return lowerCaseEventTypes();
} else if(i === 2) {
return lowerCaseEventTypes(prefix.toLowerCase());
}
}
}
return {};
}
return {
getEventTypes: getEventTypes
};
}(window, window.document));
// 添加侦听
var eventTypes = CSSAnimation.getEventTypes();
if(eventTypes.start !== undefined) {
var foo = document.getElementById('foo');
anim.addEventListener(eventTypes.start, AnimationListener, false);
anim.addEventListener(eventTypes.end, AnimationListener, false);
anim.addEventListener(eventTypes.iteration,AnimationListener ,false);
}
else {
console.log('not supported');
}
function AnimationListener(e){
// e是一个AnimationEvent对象,参看http://devdocs.io/dom_events/animationstart
if (e.animationName == "flash" && e.type.toLowerCase().indexOf("animationend") >= 0) {
// code ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment