简体   繁体   中英

Smooth scroll up in javascript

I would like to scroll up to the top smoothly with pure JS, with code not much longer than the current one. Now, it just scrolls up 1px (I think it's px)

Code snippet:

    var textdiv = document.getElementById('infoblok');
    var currentscroll = textdiv.scrollTop;
    for(i = currentscroll; i>0; i--){
      textdiv.scrollTop = currentscroll-1;
   }

There are libraries that are best suited for this task.

However, you can try this, but remember (1) the user may interact while you are scrolling which will produce undesired user experience, (2) you should do this async so that the page does not freeze.

var textdiv = document.getElementById('infoblok');
var currentscroll = textdiv.scrollTop;
var interval = setInterval(function()
{
    if( textdiv.scrollTop <= 0 ) clearInterval(interval);
    textdiv.scrollTop -= 1;
}, 10);

This example will scroll up 1px at a time every 10ms. You can play with the 1 and 10 for different scroll speed.

This may help. I just did a quick google search.

https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery

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