JQuery實現回到頂部,jquery回到頂部

來源:互聯網
上載者:User

JQuery實現回到頂部,jquery回到頂部

當一個頁面的內容比較長時,一般都在頁面的右下角的固定位置有個“回到頂部”的按鈕,點擊後,頁面的捲軸逐漸復原到頂部,本篇來描述一個它的實現過程。
首先,需要有一個按鈕

<button id="btn_top" title="回到頂部">    回到頂部</button>

然後給這個元素定位到右下角,我們使用position:fixed。下面這個按鈕加一些最基本的樣式

#btn_top {    position: fixed;    bottom: 10px;    right: 10px;    display: none;}

此時,這個按鈕並沒有顯示出來,我們需要當頁面的捲軸距離最上方有50個像素時,顯示“回到頂部”按鈕,通過JQuery來實現

$(function () {    $(window).scroll(function () {        if ($(window).scrollTop() >= 50) {            $('#btn_top').fadeIn();        }        else {            $('#btn_top').fadeOut();        }    });});

最後,我們給“回到頂部”的按鈕添加一個click事件,通過一個動畫來讓捲軸滾到最上面

$('#btn_top').click(function () {    $('html,body').animate({ scrollTop: 0 }, 500);});

好,大功告成!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.