简体   繁体   中英

smooth scroll into view vanilla javascript

Currently I have the following code to scroll to a div:

button.addEventListener('click',function(){
   element.scrollIntoView();
},false);

How can I make it smooth scrolling? (no-jQuery, no-plugin)

function animate(elem,time) {
    if( !elem) return;
    var to = elem.offsetTop;
    var from = window.scrollY;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            window.scrollTo(0,(from+step*(to-from))+1);
            if( step == 1){ clearInterval(timer);};
        },25);
        window.scrollTo(0,(from+1));
    }

var divVal = document.getElementById('yourElementID');
animate(divVal,1000);

http://jsfiddle.net/p5g4wnj9/

let me know if it helped!

scrollIntoView has a few options, try this

.scrollIntoView({behavior: 'smooth'});

I found this info on this site "developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView"

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