視差滾動通過多層背景以不同速度移動創造景深感。傳統方案綁定 scroll 事件,JS 計算位置操作 DOM,導致:
① 大量事件觸發 → 主線程阻塞
② 頻繁重排重繪 → 掉幀卡頓
③ 移動端性能災難
background-attachment: scroll | fixed | local | inherit;
scroll (預設) 背景跟隨元素滾動
fixed 背景相對視口固定,不隨元素滾動
local 背景跟隨元素內容滾動
[class*="bg__"] {
height: 50vh; /* 視口高度比例 */
background-attachment: fixed; /* 關鍵:固定於視口 */
background-position: center center;
background-size: cover; /* 覆蓋填滿 */
text-indent: -9999px; /* 隱藏文字內容 */
}
&:nth-child(2n) { box-shadow: inset 0 0 1em #111; }
<div class="bg__layer1">Layer 1</div>
<div class="bg__layer2">Layer 2</div>
<div class="bg__layer3">Layer 3</div>
<div class="bg__layer4">Layer 4</div>
滾動時,頁面內容(前景)向上移動,而 fixed 背景保持視口位置不變。不同層疊順序的固定背景產生相對運動視差。無 JS、無監聽、零重排,GPU 合成層直接處理,性能極佳。
fixed 背景附著,需媒體查詢降級或使用 transform: translate3d(0,0,0) 強制合成層。z-index 管理。will-change: transform 提示瀏覽器。<section>、aria-label 標識視差區塊,螢幕閱讀器跳過裝飾層。| 維度 | JS 監聽方案 | CSS fixed 方案 |
|---|---|---|
| 性能 | 差(主線程繁忙) | 優(合成器線程) |
| 平滑度 | 易掉幀 | 60fps 穩定 |
| 代碼量 | 百行級 | 十行級 |
| 靈活度 | 極高(任意軌跡) | 僅垂直固定視差 |
| 移動端 | 需優化節流 | 需降級處理 |
background-attachment: fixed 是實現高性能視差的「殺手鐧」。雖功能單一(僅垂直固定視差),但零依賴、零運行時開銷、聲明式語法,使其成為首屏英雄區、故事敘事長頁的首選方案。複雜軌跡視差仍需 JS,但請務必使用 IntersectionObserver + requestAnimationFrame + transform3d 優化性能。