jQuery .animate()的纯JS等效方法

33

以下是 jQuery animate 在纯 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>


element.style.top = position + "px"; - VisioN
$(element) 应该被定位为 absolute 或者 relative - Jai
@jai 是的,它是绝对定位。 - Rizwan Mumtaz
4个回答

35

使用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
}

9

这个版本使用的是原生的javascript .animate()函数,比requestAnimationFrame更好或性能更高。它也是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%确定,只是记得看过一篇文章...
请不要引用我的话!请自行研究确认,
但我编写的代码已经经过测试可以正常工作... 希望对某些人有所帮助...


此解决方案的浏览器兼容性必须进行检查,因为它并不完全支持许多浏览器。 - Tarik Merabet
1
@Tarik Merabet> 我之前在代码审查中提出的两个问题是基于尝试检查.animate() Api的兼容性并在必要时提供回退,我知道已经有polyfill和库来完成这个任务,但我想尽可能少地依赖外部代码。1)https://codereview.stackexchange.com/questions/237357/check-browser-compatibility-for-requestanimationframe-and-vanilla-javascript-an 2)https://codereview.stackexchange.com/questions/238500/javascript-anime-support-switch-statement-for-animate-api - Ryan Stone
2
2022年,浏览器支持看起来相当不错,我的看法是:https://caniuse.com/web-animation。 - Kalnode

1

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();

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接