Html
    Css
    Js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
window.onload = function() {
var obtn = document.getElementById('btn');
var clientHeight = document.documentElement.clientHeight;
var timer = null;
var isTop = true;
window.onscroll = function() {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
if (osTop >= clientHeight) {
obtn.style.display = 'block';
} else {
obtn.style.display = 'none';
}
if (!isTop) {
clearInterval(timer);
}
isTop = false;
}
//
obtn.onclick = function() {
//,setInterval(),function()
timer = setInterval(function() {
var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ispeed = Math.floor(-osTop / 5);
document.documentElement.scrollTop = document.body.scrollTop = osTop + ispeed;
isTop = true;
console.log(osTop - ispeed);
if (osTop == 0) {
clearInterval(timer);
}
}, 30);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
↑上面代码改变,会自动显示代码结果 jQuery调用版本:2.1.4
 立即下载

原生JS实现回到顶部功能

//页面加载完毕后触发
window.onload = function() {
    //用来获取存在页面的btn标签
    var obtn = document.getelementbyid('btn');
    //获取可视区的高度
    var clientheight = document.documentelement.clientheight;
    //创建存放定时器的变量
    var timer = null;
    //创建中途停止的变量
    var istop = true;
    //中途停止,onscroll事件为滚动条一滚动就触发此事件
    window.onscroll = function() {
        var ostop = document.documentelement.scrolltop || document.body.scrolltop;
        if (ostop >= clientheight) {
            obtn.style.display = 'block';
        } else {
            obtn.style.display = 'none';
        }
        if (!istop) {
            //清除定时器
            clearinterval(timer);
        }
        istop = false;
    }
    //给其添加点击事件
    obtn.onclick = function() {
        ////获取可视区的高度
        //alert(clientheight);
        //写定时器,动画效果的函数setinterval(),放一个匿名函数function()
        timer = setinterval(function() {
            // 双|表示如果不支持第一种就使用第二种
            var ostop = document.documentelement.scrolltop || document.body.scrolltop;
            //写速度,此处5为整数,为了预防非整数添加函数math.floor()包裹,因为置顶不为0所以-的ostop
            var ispeed = math.floor(-ostop / 5);
            //    //测出滑动到的位置距顶部多高
            //    alert(ostop);
            //改写滚动条的数值(此处把数值50赋值给不同的浏览器),=50直接返回距顶部200的位置,-=50是只返回200的距离
            //          document.documentelement.scrolltop = document.body.scrolltop -= 50;
            //          因为置顶不为0,还因为var ispeed = math.floor(-ostop / 5);所以ostop + ispeed
            document.documentelement.scrolltop = document.body.scrolltop = ostop + ispeed;
            //隔多久执行一次,此处为30毫秒
            //因为中途停止,此处要改为true
            istop = true;
            //后台输出 继续改进下滑不了的情况
            console.log(ostop - ispeed);
            //因为回到顶部后,下滑不执行,还仍重复回到顶部,此处加判断
            if (ostop == 0) {
                //清除定时器
                clearinterval(timer);
            }
        }, 30);
    }
}


0