510 字
3 分鐘
JavaScript focus() 讓畫面跳動?用 preventScroll 保留位置
本文目錄
側欄更新後,程式呼叫 input.focus(),結果整塊面板跳到下面。若這次只想移動鍵盤焦點並保留原本的捲動位置,改用 input.focus({ preventScroll: true })。HTML 標準把聚焦和將目標捲入畫面分成兩步,preventScroll 會略過第二步。HTML 標準的 focus() 步驟
在同一欄位量兩次
把這段存成 HTML 後用瀏覽器開啟。先按「預設聚焦」,再按「保留捲動」。範例在每次測試前把面板捲回開頭,並把焦點移到面板外的按鈕。
<!doctype html><html lang="zh-TW"><meta charset="utf-8"><title>focus 捲動對照</title><button id="with-scroll">預設聚焦</button><button id="without-scroll">保留捲動</button><div id="panel" style="height: 110px; overflow: auto; border: 1px solid"> <div style="height: 400px"></div> <label>搜尋 <input id="query"></label> <div style="height: 160px"></div></div><output id="result"></output><script> const panel = document.querySelector("#panel"); const input = document.querySelector("#query"); const result = document.querySelector("#result");
function compare(button, preventScroll) { button.addEventListener("click", () => { button.focus({ preventScroll: true }); panel.scrollTop = 0; const before = panel.scrollTop;
input.focus({ preventScroll });
result.value = JSON.stringify({ before, after: panel.scrollTop, focused: document.activeElement === input, }); }); }
compare(document.querySelector("#with-scroll"), false); compare(document.querySelector("#without-scroll"), true);</script>兩次的 focused 都應是 true。預設聚焦後,after 大於 before。保留捲動時,兩者應相同。精確像素會隨瀏覽器與版面而變,所以測試斷言應比對位置是否改變。
修復焦點後也要看焦點在哪裡
面板或對話框關閉後,若要把焦點還給仍在畫面裡的原按鈕,可以用 preventScroll 避免帶動畫面。若按鈕已滑出視窗,或你要把使用者帶到表單的第一個錯誤欄位,保留瀏覽器捲入焦點的行為會讓鍵盤操作更好追蹤。上面的例子刻意讓輸入框留在畫面外,只用來重現差異。
除錯時可以在呼叫前後同時看 document.activeElement、window.scrollY 和面板的 scrollTop。若焦點已改變,但加上 preventScroll 後畫面仍在後續跳動,再檢查其他程式是否有呼叫 scrollIntoView()、改捲動位置或重新排版。有明確的 scrollIntoView 捲錯容器 問題時,應從那次呼叫與可捲動的祖先查起。
參考資料:
JavaScript focus() 讓畫面跳動?用 preventScroll 保留位置
https://laplusda.com/posts/javascript-focus-preventscroll/