Cross browser JavaScript (not jQuery…) scroll to top animation

后端 未结 20 1194
抹茶落季
抹茶落季 2020-11-22 11:01

I\'m looking for a simple, cross-browser \"scroll to top\" animation I can apply to a link. I don\'t want to require a JS library such as jQuery/Moo, etc.

//         


        
20条回答
  •  星月不相逢
    2020-11-22 11:49

    Easy.

    var scrollIt = function(time) {
        // time = scroll time in ms
        var start = new Date().getTime(),
            scroll = document.documentElement.scrollTop + document.body.scrollTop,
            timer = setInterval(function() {
                var now = Math.min(time,(new Date().getTime())-start)/time;
                document.documentElement.scrollTop
                    = document.body.scrollTop = (1-time)/start*scroll;
                if( now == 1) clearTimeout(timer);
            },25);
    }
    

提交回复
热议问题