javascript - 使 Javascript 动画继续而不重置

标签 javascript animation

我试图让这个功能无需重置即可重复。 例如,当我按下具有此功能的按钮时,按钮将从 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/

相关文章:

javascript - 使用 Powershell 编写具有 printSelectedDiv javascript 的网页的 pdf 打印脚本

javascript - 检测我正在使用哪种类型的 d3 秤

javascript - Jquery动画效果在第一次点击时不起作用

c# - 关闭时淡出 wpf 窗口

javascript - Angular 中如何实现多线程?

javascript - 带有错误处理 FileNotFound 的文件下载 html

c# - 如何在 WPF 中有条件地执行 EventTrigger?

ios - imageView 动画出错了

javascript - 鼠标后的 div 元素链

Android展开 View 动画