有些表單頁面希望使用者不必多按一次滑鼠,游標移到輸入框上就自動聚焦。這個效果可以靠事件代理一次搞定,不必為每個欄位個別綁定。
var Page_INIT = function () {
$(document)
.bind("mouseover", function (e) { // 滑鼠移入
if (e.target.tagName.toUpperCase() == "INPUT") {
var input = e.target;
if (input.type == "text") { // 只處理文字框
if (window.Page_FocusTimer) {
window.clearTimeout(window.Page_FocusTimer);
}
// 延遲 200ms,避免游標掃過時頻繁觸發
window.Page_FocusTimer = window.setTimeout(function () {
if (!input.value) { // 內容為空才聚焦,不打斷已輸入者
try {
input.focus();
} catch (e) { }
}
}, 200);
}
}
})
.bind("mouseout", function (e) { // 滑鼠移出
if (e.target.tagName.toUpperCase() == "INPUT") {
var input = e.target;
if (input.type == "text") {
if (window.Page_FocusTimer) {
window.clearTimeout(window.Page_FocusTimer);
}
}
}
});
};
為什麼要 200ms 延遲?滑鼠從一個欄位掃到另一個欄位會經過中間的元素,若直接 focus,視線跳動會很不舒服。加一層短暫的 debounce,等游標「停下來」才動作,體驗自然許多。
為什麼判斷 input.value 為空?使用者可能只是想把游標移到某個已填寫的欄位做修改,這時搶走焦點反而造成困擾。限定空欄位,這個副作用就消失了。
為什麼用事件代理而非逐欄綁定?綁在 document 上,日後動態插入的欄位也自動生效,不必回頭補 .bind()。
目前只處理 type == "text",若頁面有 textarea、搜尋框或 type="email" 等,記得擴充判斷條件。另外建議把 tagName 判斷改成 e.target.nodeName 並搭配 instanceof HTMLInputElement 這類更穩定的寫法;而 try/catch 是為了應對某些舊版 IE 在元素不可聚焦時丟出例外,現代瀏覽器已無此困擾。
最後提醒:自動聚焦在無障礙上是需要謹慎使用的行為。鍵盤與螢幕閱讀器使用者可能因為焦點被搶而失去位置感,若決定採用,強烈建議限制在「欄位為空」的條件下,並提供關閉途徑。