我正在尝试使用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>
答案 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