JavaScript动画运动

时间:2016-03-24 03:10:58

标签: javascript animation

我正在尝试使用JavaScript制作动画,但由于我的代码无法正常工作,因此无法找到错误。我试图让蓝色的盒子从左向右倾斜移动,但它只是保持静止。请帮忙。

<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' href='style.css'/>
        <script src='script.js'></script>
        <title>Practice</title>
        <style>
        #box{
            background:red;
            width: 400px;
            height: 400px;
            position: relative;
        }

       #ani{
           background: blue;
           width: 50px;
           height: 50px;
           position: absolute;
       }
        </style>
    </head>
        <body>
             <p>
        <button onclick="animate()">OK</button>
        </p>
        <div id="box">
        <div id="ani"></div>
        </div>
          <script>
          function animate(){
              var elem = document.getElementById('ani');
              var pos = 0;
              var id = setInterval(frame,3);
              function frame(){
              if(pos == 350){
                  clearInterval(id);
              }else{
                  pos++;
                  elem.style.top = pos + "px";
                  elem.style.left = pos + "px";
              }
              }
          }
          </script>
        </body>
</html>

1 个答案:

答案 0 :(得分:2)

使用与animate不同的函数名称。 [Ref]

  

Element.animate()方法是在元素上创建和播放动画的快捷方法。声明global function animate()后,shadowed

Element.prototype.animate

试试这个:

function animateMe() {
  var elem = document.getElementById('ani');
  var pos = 0;
  var id = setInterval(frame, 3);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    }
  }
}
 #box {
   background: red;
   width: 400px;
   height: 400px;
   position: relative;
 }
 #ani {
   background: blue;
   width: 50px;
   height: 50px;
   position: absolute;
 }
<p>
  <button onclick="animateMe()">OK</button>
</p>
<div id="box">
  <div id="ani"></div>
</div>

注意:如提供的参考资料中所述,您可以使用window.animate(),因为它不会引用shadowed原型而是Global animate function

Fiddle here