如何使用style.animation的document.getElementsByClassName(" classname")

时间:2015-06-14 14:17:18

标签: javascript html css

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;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

getElementsByClassName会返回HTMLCollection,因此,您需要访问特定项目([0])或迭代 p>

&#13;
&#13;
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;
&#13;
&#13;