$(selector).animate({css屬性}, 速度, 緩動函數, 回呼函數);
<script src="jquery.min.js"></script>
<script>
$(document).ready(function($) {
// 回到頂部
$('#shang').click(function() {
$('html, body').animate({ scrollTop: '0px' }, 800);
});
// 捲動到指定元素 (#comments)
$('#comt').click(function() {
$('html, body').animate({
scrollTop: $('#comments').offset().top
}, 800);
});
// 捲動到底部 (#footer)
$('#xia').click(function() {
$('html, body').animate({
scrollTop: $('#footer').offset().top
}, 800);
});
});
</script>
<!-- 導航按鈕 -->
<button id="shang">⬆ 回頂部</button>
<button id="comt">💬 看評論</button>
<button id="xia">⬇ 到底部</button>
<div id="comments" style="margin-top:2000px;">評論區</div>
<div id="footer" style="margin-top:1000px;">頁腳</div>
$('html, body') 雙選擇器:跨瀏覽器相容。Chrome/FF 捲動 body,IE/Edge 捲動 html,雙選確保生效。.offset().top:取得元素相對文件的絕對座標,作為捲動目標。swing,可改 linear 或引入 jQuery UI 使用 easeInOutCubic 等進階緩動。var navHeight = $('#fixedNav').outerHeight(); // 固定導覽列高度
$('#comt').click(function() {
var targetTop = $('#comments').offset().top - navHeight;
$('html, body').animate({ scrollTop: targetTop }, 800);
});
$('#comt').click(function(e) {
e.preventDefault(); // 阻止預設錨點跳轉
var target = $('#comments');
var targetTop = target.offset().top - navHeight;
$('html, body').animate({ scrollTop: targetTop }, 800, function() {
// 動畫完成後更新 hash (不觸發捲動)
history.pushState(null, null, '#comments');
// 或:window.location.hash = 'comments'; (會微微跳動)
});
});
無需 jQuery,現代瀏覽器原生支援:
document.getElementById('shang').addEventListener('click', function() {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
document.getElementById('comt').addEventListener('click', function() {
var target = document.getElementById('comments');
var navHeight = document.getElementById('fixedNav').offsetHeight;
window.scrollTo({ top: target.offsetTop - navHeight, behavior: 'smooth' });
});
支援:Chrome 61+、Firefox 36+、Safari 14+、Edge 79+。IE 不支援,需 Polyfill (smoothscroll)。
aria-label 說明用途。tabindex="0" 或原生 <button>)。<a href="#main">跳過導航</a>)。