【问题标题】:add event listener error [duplicate]添加事件侦听器错误[重复]
【发布时间】:2017-08-30 18:03:07
【问题描述】:

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 不是函数 这是我的代码:

【问题讨论】:

标签: javascript html css


【解决方案1】:

在使用类进行选择时,您必须遍历所有元素并将事件绑定到每个元素。

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>

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2018-03-24
    • 2010-11-26
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多