带运动的返回顶部

1、top值的设置

2、scrollTop的变化

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="../css/public.css"/>
        <style>
            body{height: 5000px;}
            #div1{width: 100px;height: 100px;background: red;position: absolute;right: 0;top: 0;}
        </style>
        <script type="text/javascript" src="../js/rainbow.js"></script>
        <script type="text/javascript">
            window.onload=function(){
                var oDiv=document.getElementById("div1");
                var timer=null;
                var b=0;
                setTop();
                function setTop(){
                    var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
                    oDiv.style.top=scrollTop+document.documentElement.clientHeight-oDiv.offsetHeight+'px';
                }
                window.onscroll=function(){
                    setTop();
                    if(b!=1){
                        clearInterval(timer);
                    }
                    b=2;
                }
                oDiv.onclick=function(){
                    clearInterval(timer);
                    timer=setInterval(function(){
                        var iCur=document.documentElement.scrollTop || document.body.scrollTop;
                        b=1;
                        var speed=Math.floor((0-iCur)/8);
                        if(iCur==0){
                            clearInterval(timer);
                        }else{
                            document.documentElement.scrollTop = document.body.scrollTop=iCur+speed;
                        }
                    },30);
                }
            }
        </script>
    </head>
    <body>
        <div id="div1"></div>
    </body>
</html>

 

posted @ 2016-11-25 11:01  rain92  阅读(150)  评论(0编辑  收藏  举报