点击按钮回到顶部效果

前言

 

逛博客的时候发现很多人都有设置一个回到顶部的Button,觉得很实用,便在慕课网找到一个教程。并运用在博客上,喜欢的人也可以学习。

 

正文

1.代码部分

css代码

#box{
    width: 1190px;
    margin: 0 auto;
}
#btn{
    width: 40px;
    height: 40px;
    display: none;
    position: fixed;
    left: 50%;
    bottom: 30px;
    margin-left: 610px;
    background: url("images/top_bg.png" )no-repeat left top;
}
#btn:hover{
    background: url("images/top_bg.png" )no-repeat left -40px;
}

 html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>返回顶部按钮</title>
    <link href="index_top.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="index_top.js"></script>
</head>
<body>
<div id="box">
    <img src="images/tb_bg.jpg"/>
</div>
<a href="javascript:;" id="btn" title="reTop"></a>
</body>

</html>

 js代码

//页面加载完毕后触发
window.onload = function () {
    var obtn = document.getElementById('btn');
    var timer = null;
    var isTop = true;
    //获取页面可视高度
    var clientHeight = document.documentElement.clientHeight;
    //滚动条滚动时触发
    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 () {
        //设置定时器函数
        timer = setInterval(function () {

            //获取滚动条距离顶部高度
            var osTop = document.documentElement.scrollTop || document.body.scrollTop;
            //滚动速度由快变慢
            var ispeed = Math.ceil(osTop / 6);
            document.documentElement.scrollTop = document.body.scrollTop = osTop - ispeed;
            isTop = true;
            if (osTop == 0) {
                clearInterval(timer);
            }
        }, 30);

    }
}

注意事项:1.清除定时器clearInterval(timer)需要写在timer function(){}的内部。

          2.用Math.ceil()函数会比慕课网老师讲的Math.floor()好。

 

2.给博客园右端添加返回顶部按钮

1.需要申请JS权限。(点击管理—设置—申请JS权限)

2.将自己的JS文件上传到博客的文件(点击管理—文件)里,得到地址,以下是我文件里的地址。(大家可以直接使用)

       https://files.cnblogs.com/files/abao0/index_top.js

3.再将引用到的图片上传到博客的相册,得到地址,以下是我文件里的地址。(大家可以直接使用)

       http://images.cnblogs.com/cnblogs_com/abao0/975461/o_top_bg.png

4.将下面代码贴入设置的页面定制CSS代码。

#btn{
    width: 40px;
    height: 40px;
    display: none;
    position: fixed;
    left: 50%;
    bottom: 40px;
    margin-left: 610px;
    background: url("http://images.cnblogs.com/cnblogs_com/abao0/975461/o_top_bg.png" )no-repeat left top;
}
#btn:hover{
    background: url("http://images.cnblogs.com/cnblogs_com/abao0/975461/o_top_bg.png" )no-repeat left -40px;
}

5.将下面代码贴入设置的页脚Html代码。

<a href="javascript:;" id="btn" title="reTop"></a>
<script type="text/javascript" src="https://files.cnblogs.com/files/abao0/index_top.js"></script>

 

后记

 

做返回顶部效果,用jQuery的话要的确简单很多,但是建议对于初学者还是要懂原生JavaScript代码。

 

posted @ 2017-03-29 22:55  博客园小马甲  阅读(1222)  评论(1编辑  收藏  举报