纯JS等价于jQuery .animate()

Pure JS equivalent of jQuery .animate()

本文关键字:animate jQuery JS 等价于      更新时间:2023-09-26

下面的jQuery动画在纯JavaScript中的等效是什么?

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>

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

请在这里核对。

下面是移动元素的关键部分:

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
}

这个版本使用了javascript .animate()函数,这是更好或更性能
比requestAnimation帧。,它也是jquery .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: ''
        });   

我相信setTimeout &setInterval函数都在底层使用不安全的eval()函数,但不是100%确定,只要记住阅读有关它的文章…
别引用我的话!研究一下,
但是我写的代码经过测试是有效的。

setInterval()方法对于浏览器来说太重了,所以最好使用requestAnimationFrame()来制作动画。下面的代码是使用此方法的示例:

let _btns = document.querySelectorAll('.btn'),
        _start = null;
let _loop = function (timestamp, duration, position, wrap) {
        if (!_start) _start = timestamp;
        let progress = (timestamp - _start) / duration;
        wrap.style.left = progress * position + 'px'
        if ( progress < 1 ) {
            window.requestAnimationFrame( function (timestamp){
                _loop(timestamp,duration,position,wrap);
            } );
        } else {
            _start = null;
        }
    },
    _animation = function () {
        const wrap = document.querySelector('.logo-2'),
            position = 300, // 300 pixels
            duration = 500; // 500 milliseconds
        _loop(0,duration,position,wrap);
    },
    _addEvents = function () {
        [].forEach.call(_btns,function(el){
            el.addEventListener('click', function (e) {
                _animation();
            })
        });
    },
    _init = function() {
        _addEvents();
    };
_init();

Element.animate()函数似乎非常简单和有用。但目前有很多兼容性问题。你可以阅读:

https://developer.mozilla.org/en-US/docs/Web/API/Element/animate

我建议习惯requestanimationframe。它兼容所有的浏览器,它是非常强大的:

https://javascript.info/js-animation