[HTML/JS] JQuery 頁面滾動回到頂部


 HTML:

<html>
<body>

<div id="back-to-top" style="cursor:pointer; display:block;">
上升按鈕
</div>

</body>
</html>

 

 

JS:


$(function(){ //當滾動條的位置處於距頂部100像素以下時,跳轉鏈接出現,否則消失 $(function () { $(window).scroll(function(){ if ($(window).scrollTop()>100){ $("#back-to-top").fadeIn(1500); } else { $("#back-to-top").fadeOut(1500); } }); //當點擊跳轉鏈接后,回到頁面頂部位置 $("#back-to-top").click(function(){ $('body,html').animate({scrollTop:0},1000); return false; }); }); });

 

======

擴展升級:

點擊菜單按鈕, 動態滾動到對應位置.

HTML:

      <div id="header_nav">
                        <ul>
                            <li>
                                <a href="#home">首頁</a>
                            </li>
                            <li>
                                <a href="#download">下載</a>
                            </li> 
                            <li>
                                <a href="#contact">聯系</a>
                            </li>
                        </ul>

       </div>

 

JS:

// -- initial --
$(document).ready(function() {
    
    
    $("#header_nav a").click(function(){
        var selector=$(this).attr("href"); 
        var top = $(selector).offset().top;
        var current_top = $('body').scrollTop();
        var animate_time=  Math.abs( current_top - top ) * 0.8; // 800px per second. 
        $('body,html').animate({scrollTop:top},animate_time);
        return false;
    });


});

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM