JS实现回到顶部的滚动效果

//页面加载完后触发
window.onload = function () {
    var back = document.getElementById("back");
    back.onclick = function () {
        var time = setInterval(function () {
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            if (top === 0) {
                clearInterval(time);
            } else {
                document.documentElement.scrollTop = top - 20;
            }
        }, 1);
    }
};
//jquery写法
$(function () {
    $("#back").click(function () {
        var time = setInterval(function () {
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            if (top === 0) {
                clearInterval(time);
            } else {
                window.scrollTo(0, top - 100);
            }
        }, 10);
    });
});

你可能感兴趣的:(html)