JavaScript中返回顶部按钮(匀速、减速)写法

来源:互联网 发布:python split for in 编辑:程序博客网 时间:2024/05/23 19:15

1.减速运动回到顶部的方法(多数用这个):

var totop = document.getElementbyId("totop");var target = 0;totop.onclick = function () {    clearInterval(timer);    var timer = setInterval(function () {        target = document.body.scrollTop;        target -= Math.ceil(target/10);//做减速运动        window.scrollTo(0, target);        if (target == 0) {            clearInterval(timer);        }    }, 10);};

2.匀速运动到顶部(用的较少)

var totop = document.getElementById('totop');        var target = 0;            totop.onclick = function () {                clearInterval(timer);                var timer = setInterval(function () {                //随定时器达到匀速                    target = document.body.scrollTop -50;                    window.scrollTo(0, target);                    if (parseInt(target) < 60) {                        window.scroll(0, 0);                        clearInterval(timer);                    }                }, 10);            };
1 0