單頁式網站、長文目錄導航、回到頂部等,需點擊連結平滑滾動至目標區塊,而非瞬間跳轉,且不在 URL 留下 #hash 尾巴。
<script src="jquery-1.11.3.min.js"></script>
<script src="jquery.hovertreescroll.js"></script>
<script>
function scroll(id) {
$('#' + id).HoverTreeScroll(1000); // 1 秒滾動
}
</script>
<a href="javascript:scroll('hovertree');">HoverTree</a>
<div id="hovertree" style="height:800px;background:red;">...</div>
$('html, body').animate({ scrollTop: $('#elementid').offset().top }, 1000);
原理解析:
$('html, body') 同時選取兩者相容不同瀏覽器的滾動根元素。scrollTop 設定捲軸位置,$('#elementid').offset().top 取得目標元素相對文件頂端的絕對座標。1000 為動畫持續時間(毫秒)。// 形式一:四參數
.animate({prop: val}, duration, easing, completeCallback);
// 形式二:選項物件(支援 queue、step 等進階控制)
.animate({prop: val}, { duration: 1000, easing: 'swing', complete: fn, queue: true, step: fn });
scroll-behavior: smooth CSS 原生支援(現代瀏覽器),無需 JS。history.replaceState(null, '', ' ') 或 preventDefault + 手動滾動。$(document).on('click', 'a[href^="#"]', handler)。