回到顶部- 模拟

暂时适配了chrome和ie,回到顶部原生模拟

by john Chat

HTML

<div class="box">
    <img src="" alt="" width="960px" height="3000px"/>
</div>
<a href="javascript:;" id="goTop">goTop</a>

CSS

.box{
            margin:0 auto;
            text-align: center;
        }
        a{
            text-decoration: none;
            color:#fff;
            background:lightslategrey;
            padding:10px;
            text-align: center;
            vertical-align: middle;
        }
        a#goTop{
            position: fixed;
            left:90%;
            bottom:30%;
            display: none;
        }

JavaScript

window.onload = function(){
        var goTop = document.getElementById("goTop");
        var clientHeight = document.documentElement.clientHeight; // 获取可视区的高度
        var isMoving = false;
        var tid;

        window.onscroll = function(){

            var osTop = document.documentElement.scrollTop || document.body.scrollTop;
            if(osTop >= clientHeight){
                document.getElementById("goTop").style.display = "block";
            }else{
                document.getElementById("goTop").style.display = "none";
            }

            if(!isMoving){
                clearInterval(tid);
            }
            isMoving = false;

        };

        goTop.onclick = function(){
             tid = setInterval(function(){
                var osTop = document.documentElement.scrollTop || document.body.scrollTop;
                var speed = Math.floor(-osTop / 5);

                 isMoving = true;
                document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
            },30);

        };
    };