我试图通过重复更改 document.getElementById("ElementID").style.left
的值,使用 JavaScript 使元素“振动”。我在特定函数中对其进行了多次更改,但不是每次更改时都移动它,而是仅在函数末尾(即我最后一次进行更改时)移动。 HTML 代码如下:
<html>
<body>
<script>
function changePosition() {
if (document.getElementById("ElementID").style.left == "50%") {
document.getElementById("ElementID").style.left = "52%";
} else {
document.getElementById("ElementID").style.left = "50%";
}
}
function vibrate() {
changePosition();
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
setTimeout(changePosition, 50);
}
</script>
<button id="ElementID" type="button" style="position:absolute; top:50%; left:50%;" onclick="vibrate()">Vibrate Me</button>
</body>
</html>
最后我只能看到按钮应有的位置,但看不到更改期间的转换。我做错了什么?
最佳答案
似乎所有超时都会同时执行。尝试更改为这个
setTimeout(changePosition,100);
setTimeout(changePosition,200);
setTimeout(changePosition,300);
setTimeout(changePosition,400);
或
for (var i = 1; i < 5; i++) {
setTimeout(changePosition,100*i);
}
关于javascript - JavaScript 函数中的元素仅更改一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546966/