在彈窗(Modal)場景中,若彈窗內容區有滾動條,使用 <a href="#anchor"> 錨點跳轉會導致整個頁面(含彈窗上方固定區域)跟隨滾動,造成用戶體驗極差。本文提供簡潔有效的解決方案。
瀏覽器預設行為:點擊錨點鏈接時,會嘗試將目標元素滾動至視口可見區域。若彈窗內容區是 overflow: auto/scroll 的容器,而非 body,瀏覽器仍會嘗試滾動最近的可滾動祖先元素,導致外層頁面同步滾動。
<!-- HTML -->
<button class="scroll-btn" data-target="section-1">跳轉到第1區塊</button>
<div id="section-1" class="content-section">內容...</div>
<!-- JavaScript -->
document.querySelectorAll('.scroll-btn').forEach(btn => {
btn.addEventListener('click', () => {
const targetId = btn.dataset.target;
const targetEl = document.getElementById(targetId);
const scrollContainer = document.querySelector('.modal-body'); // 彈窗滾動容器
if (targetEl && scrollContainer) {
// 計算目標相對於滾動容器的偏移量
const offsetTop = targetEl.offsetTop - scrollContainer.offsetTop;
scrollContainer.scrollTo({ top: offsetTop, behavior: 'smooth' });
}
});
});
<a href="#anchor" onclick="event.preventDefault();
document.getElementById('anchor').scrollIntoView({behavior: 'smooth', block: 'start'});">
跳轉
</a>
需將彈窗內容區設為 position: fixed 或獨立滾動上下文,配合 :target 高亮目標,但靈活性較低。
href="#id" 的 <a> 標籤<button> 或 <span> 綁定點擊事件,由 JS 精確控制容器滾動.modal-body)有明確的 overflow: auto 和固定高度採用 JavaScript 方案可完全掌控滾動行為,避免瀏覽器預設行為干擾,是解決此類問題的標準做法。