var x = document.getElementsByClassName("box");
// Code for Chrome, Safari and Opera
x.addEventListener("webkitAnimationEnd", function(){
console.log("event has ended");
});
// Standard syntax
x.addEventListener("animationend", function(){
console.log("event has ended");
});
.box {
background: red;
position: absolute;
padding: 100px;
}
.box:hover {
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
<html>
<body>
<div class="box">
</div>
</body>
</html>
我正在尝试使用js和css动画,我试图在控制台日志中显示一条消息,动画已经结束但它没有出现,它给了我这个错误:x.addEventListener不是一个函数 这是我的代码:
答案 0 :(得分:0)
尝试使用如下索引:
var x = document.getElementsByClassName("box")[0];
// Code for Chrome, Safari and Opera
x.addEventListener("webkitAnimationEnd", function(){
console.log("event has ended");
});
// Standard syntax
x.addEventListener("animationend", function(){
console.log("event has ended");
});
.box {
background: red;
position: absolute;
padding: 100px;
}
.box:hover {
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
<html>
<body>
<div class="box">
</div>
</body>
</html>
答案 1 :(得分:0)
在选择使用类时,您必须遍历所有元素并将事件绑定到每个元素。
var x = document.getElementsByClassName("box");
// Code for Chrome, Safari and Opera
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("webkitAnimationEnd", function() {
console.log("event has ended");
});
// Standard syntax
x[i].addEventListener("animationend", function() {
console.log("event has ended");
});
}
&#13;
.box {
background: red;
position: absolute;
padding: 100px;
}
.box:hover {
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
&#13;
<html>
<body>
<div class="box"></div>
</body>
</html>
&#13;