焦點(focus)是鍵盤操作與表單互動的核心。搞懂誰能獲得焦點、如何取得與釋放焦點、以及哪些事件會冒泡,寫出自動聚焦、驗證提示、鍵盤導覽這類功能就會很順手。
預設只有表單元素可以,因為只有它們需要鍵盤互動:
<input type="text" value="223">
想讓 div、span 這類元素也能接焦點,先把 tabIndex 設為 -1,再呼叫 focus():
<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div元素獲得焦點</button>
<script>
btn.onclick = function(){
test.tabIndex = -1;
test.focus();
}
test.onfocus = function(){
this.style.background = 'pink';
}
</script>
document.activeElement 保存著目前獲得焦點的元素,是讀取焦點狀態最直接的方式。
<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div元素獲得焦點</button>
<script>
console.log(document.activeElement); //<body>
btn.onclick = function(){
console.log(document.activeElement); //<button>
test.tabIndex = -1;
test.focus();
console.log(document.activeElement); //<div>
}
</script>
1. 頁面載入:文件剛載入時 activeElement 是 body;載入期間則為 null。
<script>console.log(document.activeElement);</script> <!--null--> <body> <script>console.log(document.activeElement);</script> <!--<body>--> </body>
2. 使用者按 Tab:這時就必須談 tabindex。它決定元素是否被 Tab 走訪,以及走訪的優先順序:
tabindex="-1":Tab 會跳過這個元素(但仍可用 JS 聚焦)。tabindex="0":Tab 會走訪,未設定時預設就是 0。tabindex 大於 0:優先走訪,數值越大優先級反而越低。下列程式中,按 Tab 的聚焦順序是 2 → 5 → 1 → 3(4 被跳過):
<div id="box">
<button tabindex="3">1</button>
<button tabindex="1">2</button>
<button tabindex="0">3</button>
<button tabindex="-1">4</button>
<button tabindex="2">5</button>
</div>
<script>
box.onkeyup = function(){
document.activeElement.style.background = 'pink';
}
</script>
實務建議:正數 tabindex 會破壞正常的文件順序,對使用螢幕閱讀器的人造成困擾,除非有特殊需求,一律只用 0 與 -1。
3. focus() 方法:把焦點設到指定欄位,讓它開始接收鍵盤事件。
<span id="test1" style="height:30px;width:100px;">span</span>
<input id="test2" value="input">
<button id="btn1">span元素獲得焦點</button>
<button id="btn2">input元素獲得焦點</button>
<script>
btn1.onclick = function(){ test1.tabIndex = -1; test1.focus(); }
btn2.onclick = function(){ test2.focus(); }
</script>
4. autofocus 屬性:HTML5 新增,不用一行 JS 就能自動聚焦。但它只對表單元素有效,普通元素即使設了 tabindex="-1" 也不會生效。
<input autofocus value="abc">
document.hasFocus() 回傳布林值,代表目前文件是否有元素處於焦點狀態。常用來判斷使用者是否已切到別的分頁,例如暫停動畫或暫停計時。
console.log(document.hasFocus()); //true
//兩秒內切到其他分頁,讓焦點離開目前頁面
setTimeout(function(){
console.log(document.hasFocus()); //false
}, 2000);
blur() 的作用是把焦點從元素上移走。注意它不會把焦點轉移給某個特定元素,只是單純讓目前元素放手。
<input id="test" type="text" value="123">
<button id="btn1">input元素獲得焦點</button>
<button id="btn2">input元素失去焦點</button>
<script>
btn1.onclick = function(){ test.focus(); }
btn2.onclick = function(){ test.blur(); }
</script>
| 事件 | 觸發時機 | 是否冒泡 |
|---|---|---|
blur | 元素失去焦點 | 不冒泡 |
focus | 元素獲得焦點 | 不冒泡 |
focusin | 元素獲得焦點(等價 focus) | 會冒泡 |
focusout | 元素失去焦點(等價 blur) | 會冒泡 |
因為 focus 與 blur 不冒泡,無法用事件 delegates 在父層統一攔截,這正是 focusin / focusout 存在的意義。要注意的是,focusin 與 focusout 早期只有 IE 以 DOM0 等級支援,其他瀏覽器僅支援 DOM2,因此實作時仍應做能力檢測:
<div id="box" style="display:inline-block;padding:25px;background-color:lightgreen;">
<div id="boxIn" style="height:50px;width:50px;background-color:pink;">123</div>
</div>
<button id="btn1">內容為123的div元素獲取焦點</button>
<button id="btn2">內容為123的div元素失去焦點</button>
<button id="reset">還原</button>
<script>
reset.onclick = function(){ history.go(); }
btn1.onclick = function(){ boxIn.tabIndex = -1; boxIn.focus(); }
btn2.onclick = function(){ boxIn.blur(); }
//focusin 事件(會冒泡,所以父層也會被觸發)
if (boxIn.addEventListener) {
boxIn.addEventListener('focusin', handler);
box.addEventListener('focusin', handler);
} else {
boxIn.onfocusin = handler;
box.onfocusin = handler;
}
function handler(){ this.style.backgroundColor = 'lightblue'; }
//blur 事件(不冒泡)
function fnBlur(){ this.style.backgroundColor = 'orange'; }
boxIn.onblur = fnBlur;
box.onblur = fnBlur;
</script>
執行結果可以印證:焦點在 boxIn 上時,父層 box 也會變色(focusin 冒泡上來了);但失去焦點時只有 boxIn 變色,父層毫無反應。
把 focusin / focusout 掛在容器上,就能用一份程式碼處理所有欄位——這正是事件 delegates 的價值。
<div id="box">
<input id="input1" type="text" placeholder="只可以輸入數字">
<input id="input2" type="text" placeholder="只可以輸入漢字">
<span id="tips"></span>
</div>
<script>
if (box.addEventListener) {
box.addEventListener('focusin', fnIn);
box.addEventListener('focusout', fnOut);
} else {
box.onfocusin = fnIn;
box.onfocusout = fnOut;
}
function fnIn(e){
e = e || event;
var target = e.target || e.srcElement;
target.style.backgroundColor = 'lightgreen';
}
function fnOut(e){
e = e || event;
var target = e.target || e.srcElement;
target.style.backgroundColor = 'initial';
//驗證數字的欄位
if (target === input1) {
if (!/^\d*$/.test(target.value.trim())) {
target.focus();
tips.innerHTML = '只能輸入數字,請重新輸入';
setTimeout(function(){ tips.innerHTML = '' }, 500);
}
}
//驗證漢字的欄位
if (target === input2) {
if (!/^[\u4e00-\u9fa5]*$/.test(target.value.trim())) {
target.focus();
tips.innerHTML = '只能輸入漢字,請重新輸入';
setTimeout(function(){ tips.innerHTML = '' }, 500);
}
}
}
</script>
記住四件事就夠:只有表單元素預設可得焦點,其他元素要設 tabIndex="-1";document.activeElement 讀取目前焦點、hasFocus() 判斷分頁是否處於活動狀態;focus() 給焦點、blur() 移走焦點;focusin / focusout 會冒泡而 focus / blur 不會,需要事件 delegates 時務必選前者。