gpt4 book ai didi

JavaScript 动画运动

转载 作者:行者123 更新时间:2023-12-02 14:51:05 26 4
gpt4 key购买 nike

我正在尝试用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com