简体   繁体   中英

jQuery animate function equivalent in pure JavaScript

What is the equivalent of the following jQuery animate in pure 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>

You can acheive complex animations with pure javascript by using setTimeout and setInterval methods.

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
}

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

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...

Element.animate() function seems to be very simple and useful. But there are for now a lot of compatibility issues. You can read about it:

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

I would recommend to get used to requestAnmationFrame. It's compatible with all browsers and it is very powerful:

https://javascript.info/js-animation

The setInterval() method is too heavy for the browser, so it's better to use requestAnimationFrame() for animations. The following code is an example of using this method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM