DIV CSS 佈局教程網

兩行 jQuery 就能做的返回頂部與底部平滑滾動動畫
編輯:JQuery特效代碼     

頁面內容很長時,加上「回到頂部」與「移到頁尾」的按鈕會方便很多。透過 jQuery 的 animate() 搭配 scrollTop,只要短短幾行就能實現平滑捲動。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script>
$(document).ready(function () {
    // 點擊頂部按鈕時,捲動到頂端;scrollTop 可取得或設定捲動距離
    $('#top').click(function () {
        $('html').animate(
            { scrollTop: '0px' }, 1000
        );
    });
    // 點擊底部按鈕時,offset() 取得元素相對視口的偏移量(含 top、left 兩個屬性)
    // animate 的第二個參數也可設為 'slow'、'normal' 或 'fast'
    $('#foot').click(function () {
        $('html').animate(
            {scrollTop:$('span').offset().top},1000
        );
    });
});
</script>
</head>
<body>
<br /><br /><br /><br /><br />
<a href="#" id="foot">底部</a>
<br /><br /><br /><br /><br />
<br /><br /><br /><br /><br />
<a href="#" id="top">頂部</a>
<br /><br /><br /><br /><br />
<span></span>
</body>
</html>

原理很單純:點擊頂部按鈕時把 scrollTop 動畫到 0px;點擊底部按鈕時,先用 offset().top 取得目標元素的位置,再捲動過去。第二個參數 1000 代表動畫歷時 1000 毫秒,也可換成 slow、normal、fast 等關鍵字。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved