我正在尝试用 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 whenglobal function
animate()
is declared, it isshadowed
byElement.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),而是全局动画函数
关于JavaScript 动画运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36192631/