getElementbyID有效,因为ID必须是唯一的,因此该函数始终只返回一个元素(如果没有找到则返回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>
&#13;
答案 0 :(得分:0)
getElementsByClassName会返回HTMLCollection
,因此,您需要访问特定项目([0])或迭代 p>
function myFunction() {
document.getElementsByClassName("myDIV")[0].style.WebkitAnimation = "mynewmove 4s 2";
document.getElementsByClassName("myDIV")[0].style.animation = "mynewmove 4s 2";
}
&#13;
.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;
}
}
&#13;
<button onclick="myFunction()">Try it</button>
<div class="myDIV"></div>
&#13;