直接設定 `document.documentElement.scrollLeft = 300` **在頁面載入時無效**,因為瀏覽器尚未完成佈局、滾動容器尚未就緒。必須在「佈局完成」後執行,或使用動畫 API。
| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| jQuery animate | 需平滑動畫、支援舊瀏覽器 | 語法簡單、自動處理 html/body 兼容 | 需引入 jQuery、動畫佔用主執行緒 |
| 原生 scrollTo | 現代瀏覽器、無動畫需求 | 零依賴、高效能 | 無緩動效果、需自行兼容 html/body |
| CSS scroll-snap | 全屏翻頁、輪播 | 無 JS、效能最佳 | 不支援任意位置滾動 |
| IntersectionObserver | 滾動到某元素可視 | 非阻塞、響應式 | 不直接控制滾動位置 |
$(function () {
// 水平滾動 300px,1 秒緩動
$('html, body').animate({ scrollLeft: '300px' }, 1000);
// 垂直滾動
$('html, body').animate({ scrollTop: '300px' }, 1000);
// 滾動到特定元素
$('html, body').animate({
scrollTop: $('#target').offset().top
}, 800, 'swing');
});
// 等待佈局穩定(關鍵)
window.addEventListener('load', () => {
// 方法 1:window.scrollTo(視窗滾動)
window.scrollTo({ left: 300, top: 0, behavior: 'smooth' });
// 方法 2:element.scrollTo(容器滾動)
document.documentElement.scrollTo({ left: 300, behavior: 'smooth' });
// 或
document.body.scrollTo({ left: 300, behavior: 'smooth' });
// 方法 3:滾動到元素
document.getElementById('target').scrollIntoView({
behavior: 'smooth',
inline: 'center', // 水平置中
block: 'nearest'
});
});
// 獲取真正的滾動容器(跨瀏覽器)
function getScrollContainer() {
// 標準模式下 document.documentElement 是滾動容器
// 怪異模式下是 document.body
// 現代瀏覽器統一用 document.scrollingElement (Chrome 61+, FF 59+)
return document.scrollingElement || document.documentElement || document.body;
}
// 通用滾動函數
function scrollToPosition(x, y, smooth = true) {
const container = getScrollContainer();
if (container.scrollTo) {
container.scrollTo({ left: x, top: y, behavior: smooth ? 'smooth' : 'auto' });
} else {
// 降級
container.scrollLeft = x;
container.scrollTop = y;
}
}
// 使用
window.addEventListener('load', () => scrollToPosition(300, 0));
// 頁面卸載前保存
window.addEventListener('beforeunload', () => {
sessionStorage.setItem('scrollPos', JSON.stringify({
x: window.scrollX,
y: window.scrollY,
url: location.href
}));
});
// 載入時恢復
window.addEventListener('load', () => {
const saved = sessionStorage.getItem('scrollPos');
if (saved) {
const { x, y, url } = JSON.parse(saved);
if (url === location.href) { // 僅同頁恢復
scrollToPosition(x, y, false); // 無動畫瞬間恢復
}
}
});
頁面載入後自動滾動,**關鍵在時機(load 事件)與容器選擇(scrollingElement)**。現代專案優先使用原生 `scrollTo({behavior:'smooth'})`,僅在需支援 IE 或複雜緩動曲線時引入 jQuery animate。