DIV CSS 佈局教程網

jQuery 實作回到頂部與跳到底部(錨點替代方案)
編輯:JQuery特效代碼     

傳統錨點(<a href="#top">)只能瞬間跳,沒有過渡動畫。改用 jQuery 的 animate() 就能做出平滑捲動的效果。

程式碼

<script type="text/javascript">
jQuery(function(){
    $('#tophovertree').click(function(){
        $('html,body').animate({ scrollTop: '0px' }, 1000);
        return false;
    });
    $('#foothovertree').click(function(){
        $('html,body').animate({ scrollTop: $(document).height() }, 1000);
        return false;
    });
})
</script>

兩個按鈕共用同一套邏輯,只差在捲動目標:回到頂部是 0px,跳到底部是 $(document).height()。1000 代表動畫歷時一秒,可依需求調整;數值越小越快。

一樣要留意 return false,用來阻止 href="#" 造成的跳轉與網址變化。

完整程式碼

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery實現"跳到底部","回到頂部"效果(類似錨)</title>
<script type="text/javascript" src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
 jQuery(function(){
 $('#tophovertree').click(function(){ $('html,body').animate({scrollTop: '0px'}, 1000);return false;});
 $('#foothovertree').click(function(){ $('html,body').animate({scrollTop:$(document).height()},1000);return false;});
 })
</script>
</head>
<body>
<a href="#" id="foothovertree">跳到底部</a>
<br /><br /><br /><br />
<a href="#" id="tophovertree"> 返 回 頂 部 </a>
<br /><br /><br /><br />
<a name="footerhovertree" id="footerhovertree"></a>
</body>
</html>

最後那個 <a name="footerhovertree"> 保留了傳統錨點的做法,若你希望網址列帶上可被分享的錨點,可以在動畫的 callback 中改用 location.hash 設定,兼得平滑效果與可分享性。

返 回 頂 部

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