【JS基础】返回顶部效果

来源:互联网 发布:2017php视频教程百度云 编辑:程序博客网 时间:2024/05/29 11:47

参考视频:http://www.imooc.com/learn/65

html/css部分

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <script src="返回顶部效果.js"></script><style>    .container{        width:1190px;        margin: 0px auto;    }    .container a{        display: none;        width:40px;        height:40px;        background: url(http://img.mukewang.com/535e0dc100010e9c00400080.jpg) no-repeat;        position: fixed;        left:95%;        bottom: 50px;    }    .container a:hover{        background: url(http://img.mukewang.com/535e0dc100010e9c00400080.jpg) no-repeat;        background-position: left -40px;    }</style>    </head><body>    <div class="container">        <img src="http://img.mukewang.com/535e0ce800015b7511902787.jpg" alt="">        <a id="btn" href="javascript:" class="btn" title="回到顶部"></a>    </div></body></html>

JS部分

window.onload=function(){    var obtn=document.getElementById("btn");    var clientHeight=document.documentElement.clientHeight||ocument.body.clientHeight;    var isTop=true;    var timer=null;    window.onscroll=function(){        var topH=document.documentElement.scrollTop||document.body.scrollTop;        if(topH>clientHeight){            obtn.style.display="block";        }else{            obtn.style.display="none";        }    }    obtn.onclick=function(){        timer=setInterval(function(){            var topH=document.documentElement.scrollTop||document.body.scrollTop;            var stepLength=Math.ceil(topH/5);            document.documentElement.scrollTop=document.body.scrollTop=topH-stepLength;            if(topH==0){                clearInterval(timer);            }        },30);    }}
0 0
原创粉丝点击