回到頂部 特效 附源碼

<html>

<head>

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 <title>回到頂部</title>

 <style>

   .empty{height:900px; width:100%;}

   .empty span{font-size: 500px;}

   .goTop{

     z-index: 300;

     position: fixed;

     bottom: 5%;

     right: 100px;

     width: 65px;

     height: 50px;

     display: none;

     background: url(p_w_picpaths/top.png) no-repeat center 0

   }

   .goTop:hover{

     background: url(p_w_picpaths/htop.png) no-repeat center 0

   }

 </style>

 <script>

   window.onscroll = function () {

       if (document.documentElement.scrollTop + document.body.scrollTop > 100) {

           document.getElementById("goTop").style.display = "block";

       }

       else {

           document.getElementById("goTop").style.display = "none";

       }

   }


    /**

    * 回到頁面頂部

    * @param acceleration 加速度

    * @param time 時間間隔 (毫秒)

    **/

   function goTop(acceleration, time) {

       acceleration = acceleration || 0.1;

       time = time || 16;


       var x1 = 0;

       var y1 = 0;

       var x2 = 0;

       var y2 = 0;

       var x3 = 0;

       var y3 = 0;


       if (document.documentElement) {

           x1 = document.documentElement.scrollLeft || 0;

           y1 = document.documentElement.scrollTop || 0;

       }

       if (document.body) {

           x2 = document.body.scrollLeft || 0;

           y2 = document.body.scrollTop || 0;

       }

       var x3 = window.scrollX || 0;

       var y3 = window.scrollY || 0;


       // 滾動條到頁面頂部的水平距離

       var x = Math.max(x1, Math.max(x2, x3));

       // 滾動條到頁面頂部的垂直距離

       var y = Math.max(y1, Math.max(y2, y3));


       // 滾動距離 = 目前距離 / 速度, 因爲距離原來越小, 速度是大於 1 的數, 所以滾動距離會越來越小

       var speed = 1 + acceleration;

       window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));


       // 如果距離不爲零, 繼續調用迭代本函數

       if(x > 0 || y > 0) {

           var invokeFunction = "goTop(" + acceleration + ", " + time + ")";

           window.setTimeout(invokeFunction, time);

       }

   }

</script>


</head>

<body>

<div class="empty" style="background:#cccccc;"><span>1</span></div>

<div class="empty" style="background:#9999FF;"><span>2</span></div>

<div class="empty" style="background:#CCCCFF;"><span>3</span></div>


<div class="goTop" id="goTop" onclick="goTop()"></div>


</body>

</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章