我制作了一个 JSFiddle 来显示问题 http://jsfiddle.net/molokoloco/yvTje/
简而言之,我在 animationStart 事件上放置了一些监听器,向元素添加了一个新类,然后在我做的插件中,我需要检查元素是否有动画(可以与类相关联)在做或不做某事之前。
我的问题是我必须等待 25/80 毫秒才能检查动画是否开始......
我做错了什么或有什么建议?
var animationStarted = false,
s = '';
var listener = function(e) {
switch (e.type) {
case "animationstart":
case "webkitAnimationStart":
// BUT "animationstart" do not trigger instantaneously
// For the moment i compute 25 milliseconds on my Chrome & FF
var diff = (new Date().getTime()) - s;
console.log('animationStarted after ' + diff + ' ms'); // HERE THE RESULT : 30ms
break;
}
};
var setup = function() {
var e = document.getElementById("watchme");
e.addEventListener("animationstart", listener, false);
e.addEventListener("webkitAnimationStart", listener, false);
// HERE WE ADD THE CLASS
e.className = "slidein";
s = new Date().getTime(); // Time at witch the class (with anim) is applyed
};
setup();
最佳答案
甚至在尝试开始动画之前就使用特征检测。
var div = document.createElement("DIV");
div.style["animation"] = "animName 5s infinite";
div.style["WebkitAnimation"] = "animName 5s infinite";
if (div.style["animationDuration"] == "5s") {
// Supports animation
} else (div.style["WebkitAnimationDuration"] == "5s") {
// Supports -webkit-animation
}
这测试浏览器使用速记设置单个样式属性的能力。如果您只是设置一个值并以相同的方式读回它,您将得到误报。
编辑:抱歉,误解了问题。
关于使用事件检查内容,您可能需要等待几毫秒,无论您做什么...您可以使用 document.styleSheets 检查样式定义本身,但这会非常累人,具体取决于css 的特殊性。
var animationName = "";
for (var i = 0; i < document.styleSheets.length; ++i) {
var sheet = document.styleSheets[i];
var rules = sheet.cssRules || sheet.rules;
for (var j = 0; j < rules.length; ++j) {
var rule = rules[j];
if (theElement.matchesSelector(rule.selectorText)) {
var theStyle = rule.style;
animationName = theStyle["WebkitAnimationName"];
}
}
}
这是一种非常粗糙的方式,我知道...
关于javascript - 延迟 25/30 毫秒的 CSS3 animationStarted 事件触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428838/