JavaScript 动画运动

标签 javascript animation

我正在尝试用 JavaScript 制作动画,但有一个错误我找不到,因为我的代码无法工作。我试图让蓝色盒子从左向右对 Angular 移动,但它只是保持静止。请帮忙。

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";
    }
  }
}
#box {
  background: red;
  width: 400px;
  height: 400px;
  position: relative;
}

#ani {
  background: blue;
  width: 50px;
  height: 50px;
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
  <link rel='stylesheet' href='style.css' />
  <script src='script.js'></script>
  <title>Practice</title>
</head>

<body>
  <p>
    <button onclick="animate()">OK</button>
  </p>
  <div id="box">
    <div id="ani"></div>
  </div>
</body>

</html>

最佳答案

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

The Element.animate() method is a shortcut method for creating and playing an animation on an element. And when global function animate() is declared, it is shadowed by 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原型(prototype),而是全局动画函数

Fiddle here

关于JavaScript 动画运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192631/

相关文章:

javascript - knockout ,可选表格行

javascript - 使用 Webkit/jQuery 将外部页面加载到当前页面的最佳方式

css - Adobe Edge Prototype (Try) 下载链接/html5-css3 动画工具

android - 如何在 Android 上模拟 Google Plus 投票动画

css - 背景图片 CSS3 无限循环动画

javascript - 如何在 IE (>10) 和 Edge 中推送浏览器的历史记录?

php - 将多个值从 javascript 传递到 php 文件

jquery - 在 jquery 中停止父函数时防止回调被停止?

javascript - jquery 搜索过滤器 - 如果搜索不匹配,选项将被隐藏,但 optgroup 仍显示,如何隐藏 optgroup

javascript - Facebook Graph API - 让 friend 参加事件?