2017-04-05 260 views
0

添加事件侦听器的错误

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> 
 
\t 
 
\t <body> 
 
\t 
 
\t <div class="box"> 
 
\t </div> 
 

 
    
 
\t </body> 
 
</html>

我试图使用的CSS动画JS,我尝试在控制台日志中显示一条消息,该动画已经结束,但它没有出现,它给了我这个错误:x.addEventListener不是函数 这里是我的代码:

+1

'getElement ** **š返回ByClassName''HTMLCollection'即许多元件** **š。您需要遍历它并为每个元素添加侦听器。 –

+0

另外一个[querySelectorAll','getElementsByClassName'和其他'getElementsBy *'方法返回什么?](http://stackoverflow.com/q/10693845/4642212)。 – Xufox

回答

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> 
 
\t 
 
\t <body> 
 
\t 
 
\t <div class="box"> 
 
\t </div> 
 

 
    
 
\t </body> 
 
</html>

+0

如果有多个具有相同类名的元素会怎么样? –

+0

@Dan Philip,现在只有一个元素。你不能确定会有多个元素。如果只有一个元素,并且您正在使用循环,那么这取决于您。 – Mamun

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"); 
 
    }); 
 

 
}
.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>