手记

回到顶部按钮

滚动条滚动到下一屏出现回到顶部按钮,点击回到顶部按钮滚动条回到顶部。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Javascript 回到顶部效果</title>
        <style>
            #btn {
                width:40px;
                height:40px;
                position:fixed;
                left:50%; 
                display:none;
                margin-left:610px;
                bottom:30px; 
                background:url(http://img.mukewang.com/535e0dc100010e9c00400080.jpg) no-repeat left top;
            }
            #btn:hover {    
                background:url(http://img.mukewang.com/535e0dc100010e9c00400080.jpg) no-repeat 0 -39px;
            }
            .box {
                width:1190px; 
                margin:0 auto; 
            }
    </style>
    </head>
    <body>
        <div class="box">
            <img src="http://img.mukewang.com/535e0ce800015b7511902787.jpg" />
        </div>
        <a href="javascript:;" id="btn" title="回到顶部"></a>
        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
        <script>
            window.onload=function(){
                var btn=document.getElementById("btn");
                var scrollTop=0;
                var timer=null;
                
                window.onscroll=function(){
                    scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
                    //可视区域
                    var clientHeight=document.documentElement.clientHeight||document.body.clientHeight;
                    if(scrollTop-clientHeight>0){
                        document.getElementById('btn').style.display="block";
                    }else{
                        btn.style.display="none";
                    }
                }
                btn.onclick=function(){
                    newScrollTop=document.documentElement.scrollTop||document.body.scrollTop;
                    timer=setInterval(function(){
                        if(scrollTop==0){
                            clearInterval(timer);                            
                        }
                        document.documentElement.scrollTop=document.body.scrollTop=0;
                    },30)
                }
            }
        </script>
    </body>
</html>


12/21

0人推荐
随时随地看视频
慕课网APP