纯 JavaScript 中等效的 jQuery 动画函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15521081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:04:42  来源:igfitidea点击:

jQuery animate function equivalent in pure JavaScript

javascriptjquery

提问by Rizwan Mumtaz

What is the equivalent of the following jQuery animate in pure JavaScript?

纯 JavaScript 中以下 jQuery 动画的等效项是什么?

function animate(element, position, speed) {
  $(element).animate({
    "top": position
  }, speed);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

回答by Suresh Atta

You can acheive complex animations with pure javascript by using setTimeoutand setIntervalmethods.

您可以通过使用setTimeoutsetInterval方法使用纯 javascript 实现复杂的动画。

Please check here.

请检查这里

Here is the key part of moving an element:

这是移动元素的关键部分:

function move(elem) {
    var left = 0
    function frame() {
        left++  // update parameters
        elem.style.left = left + 'px' // show frame
        if (left == 100)  // check finish condition
            clearInterval(id)
    }
    var id = setInterval(frame, 10) // draw every 10ms
}

回答by Ryan Stone

This version uses vanilla javascript .animate() function, which is better or more performant
than requestAnimation frame. & it is also the proper alternative to JQuerys .animate().
you can play around with the iterations, timing functions & fill method aswell as daisy chain it with other animations

此版本使用 vanilla javascript .animate() 函数,它
比 requestAnimation 框架更好或更高效。& 它也是 JQuerys .animate() 的合适替代品。
您可以使用迭代、计时函数和填充方法以及将其与其他动画菊花链

document.getElementById("Elem");
         Elem.style.position = "absolute";
         Elem.animate({
              top: ['8px', '280px']
                 },{ duration: 1760,        // number in ms [this would be equiv of your speed].
                     easing: 'ease-in-out',
                     iterations: 1,         // infinity or a number.
                  // fill: ''
        });   

I believe the setTimeout & setInterval functions both use the unsafe eval() function under the hood, but not 100% sure about that, just remember reading an article about it...
Don't Quote me on that! just research it,
but the code I wrote out has been tested to be working.. hope this helps someone...

我相信 setTimeout 和 setInterval 函数都在幕后使用了不安全的 eval() 函数,但不是 100% 肯定,只要记得阅读一篇关于它的文章......
不要引用我的话!只是研究一下,
但我写的代码已经过测试可以正常工作..希望这对某人有帮助......