我试图让这个功能无需重置即可重复。 例如,当我按下具有此功能的按钮时,按钮将从 0px 向右移动到 100px。当我再次按下按钮时,它会从 100 像素变为 200 像素,依此类推。它也应该具有动画效果,因此它一次移动 1px,直到循环结束。
下面的代码只能一次性使用,因为它会从 0px 移动到 100px,再次按下它会使其从 0px 移动到 100px。
我已经为此工作了几个小时,并在提出请求之前查看了许多帮助来源。
function goRight() {
var pos = 0;
var count = pos;
var elem = document.getElementById("main");
var id = setInterval(move, 5);
function move() {
if(pos == count + 100){elem.style.left = pos + 'px'; clearInterval(id);}
else {pos++; elem.style.left = pos + 'px';}
}
}
最佳答案
function goRight() {
var elem = document.getElementById("main"); // the element
var origin = parseInt(elem.style.left) || 0; // get the left of the element (as an origin for the animation), 0 if not set yet
var pos = 0; // pos initialized to 0
var id = setInterval(move, 5);
function move() {
if(pos == 101) { clearInterval(id); } // if pos is 101, then stop the animation
else { pos++; elem.style.left = (origin + pos) + 'px';} // if not, then increment it and set the left of the element to pos + origin
}
}
关于javascript - 使 Javascript 动画继续而不重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42381410/