因为ID必须是唯一的,所以getElementbyID起作用,因此该函数始终仅返回一个元素(如果未找到,则返回null)。
被班级名称打中了。
如何将style.animation添加到类名?
function myFunction() {
document.getElementsByClassName("myDIV").style.WebkitAnimation = "mynewmove 4s 2";
document.getElementsByClassName("myDIV").style.animation = "mynewmove 4s 2";
}
.myDIV {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: mymove 1s infinite;
/* Chrome, Safari, Opera */
animation: mymove 1s infinite;
}
@-webkit-keyframes mymove {
from {
left: 0px;
}
to {
left: 200px;
}
}
@-webkit-keyframes mynewmove {
from {
top: 0px;
}
to {
top: 200px;
}
}
@keyframes mymove {
from {
left: 0px;
}
to {
left: 200px;
}
}
@keyframes mynewmove {
from {
top: 0px;
}
to {
top: 200px;
}
}
<button onclick="myFunction()">Try it</button>
<div class="myDIV"></div>
最佳答案
getElementsByClassName返回一个HTMLCollection
,因此,您需要访问特定的项目([0])或对其进行迭代
function myFunction() {
document.getElementsByClassName("myDIV")[0].style.WebkitAnimation = "mynewmove 4s 2";
document.getElementsByClassName("myDIV")[0].style.animation = "mynewmove 4s 2";
}
.myDIV {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: mymove 1s infinite;
/* Chrome, Safari, Opera */
animation: mymove 1s infinite;
}
@-webkit-keyframes mymove {
from {
left: 0px;
}
to {
left: 200px;
}
}
@-webkit-keyframes mynewmove {
from {
top: 0px;
}
to {
top: 200px;
}
}
@keyframes mymove {
from {
left: 0px;
}
to {
left: 200px;
}
}
@keyframes mynewmove {
from {
top: 0px;
}
to {
top: 200px;
}
}
<button onclick="myFunction()">Try it</button>
<div class="myDIV"></div>