回到顶部效果

来源:互联网 发布:手机看片软件 编辑:程序博客网 时间:2024/05/21 06:42

主要用到的知识:
慕课网截图
获取滚动条距离顶部的高度:

  1. document.documentgetElement.scrollTop(IE)

  2. document.body.scrollTop(chrome)

获取页面可视区的高度:

  1. document.documentElement.clientHeight
  2. document.body.clientHeight

<a href="#">点击a锚点可直接回到顶部
注意:

  1. 点击时速度由快到慢
  2. 滚动条滑到第二页面才出现

var osTop = document.documentElement.scrollTop || document.body.scrollTop;
var ispeed = Math.floor(-osTop / 6);
document.documentElement.scrollTop = document.body.scrollTop = osTop +ispeed;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />    <title>Javascript 返回顶部</title>    <style type="text/css">        #btn {width:40px; height:40px; position:fixed; right:65px; bottom:10px; display:none; background:url(images/top_bg.png) no-repeat left top;}        #btn:hover {background:url(images/top_bg.png) no-repeat 0 -39px;}        .bg {width:1190px; margin:0 auto;}    </style>    <script type="text/javascript">        window.onload = function(){            var obtn = document.getElementById('btn');            //获取页面可视区的高度            var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;            var timer = null;            var isTop = true;            obtn.onclick = function(){                //设置定时器                timer = setInterval(function(){                //获取滚动条距离顶部的高度                    var osTop = document.documentElement.scrollTop || document.body.scrollTop;                    if (osTop >= clientHeight){                        toTopButton.style.display = "block";                    }else {                        toTopButton.style.display = "none";                    }                    if (!isTop){                        clearInterval(timer);                    }                    isTop = false;                var ispeed = Math.floor(-osTop / 6);                document.documentElement.scrollTop = document.body.scrollTop = osTop +ispeed;                isTop = true;                if (osTop == 0){                    clearInterval(timer);                }            },30);         };    };    </script></head><body>    <a href="javascript:;" id="btn" title="回到顶部"></a>    <div class="bg">        <img src="images/tb_bg.jpg" alt="" />    </div></body></html>

以上根据慕课网回到顶部效果视频总结

0 0
原创粉丝点击