# JavaScript怎么處理焦點
## 1. 焦點基礎概念
在Web開發中,"焦點"(Focus)是指當前接收用戶輸入(如鍵盤輸入)的頁面元素。常見的可聚焦元素包括:
- `<input>`
- `<textarea>`
- `<select>`
- `<button>`
- `<a>`(帶有href屬性)
- 任何設置了`tabindex`屬性的元素
```html
<input type="text" id="username">
<button id="submit">提交</button>
使用focus()方法可以使元素獲得焦點:
document.getElementById('username').focus();
使用blur()方法可以移除元素的焦點:
document.getElementById('username').blur();
通過document.activeElement可以獲取當前獲得焦點的元素:
if (document.activeElement === document.getElementById('username')) {
console.log('用戶名輸入框已聚焦');
}
JavaScript提供了多個焦點相關的事件:
| 事件類型 | 觸發時機 |
|---|---|
| focus | 元素獲得焦點時 |
| blur | 元素失去焦點時 |
| focusin | 元素即將獲得焦點(冒泡) |
| focusout | 元素即將失去焦點(冒泡) |
const input = document.getElementById('username');
input.addEventListener('focus', function() {
this.style.borderColor = 'blue';
});
input.addEventListener('blur', function() {
this.style.borderColor = '';
});
document.addEventListener('focusin', function(e) {
if (e.target.tagName === 'INPUT') {
e.target.classList.add('highlight');
}
});
document.addEventListener('focusout', function(e) {
if (e.target.tagName === 'INPUT') {
e.target.classList.remove('highlight');
}
});
通過tabindex可以控制Tab鍵導航順序:
tabindex="0":元素可聚焦,按DOM順序導航tabindex="-1":元素可編程聚焦,但不在Tab序列中tabindex="1+":按數值順序優先聚焦(不推薦)<div tabindex="0">可聚焦的div元素</div>
document.querySelectorAll('button').forEach(btn => {
btn.tabIndex = -1; // 從Tab序列中移除
});
function createFocusTrap(container) {
const focusableElements = container.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
container.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === firstElement) {
e.preventDefault();
lastElement.focus();
} else if (!e.shiftKey && document.activeElement === lastElement) {
e.preventDefault();
firstElement.focus();
}
}
});
}
// 頁面加載后自動聚焦第一個輸入框
window.addEventListener('DOMContentLoaded', () => {
const firstInput = document.querySelector('input, textarea, select');
if (firstInput) firstInput.focus();
});
// 表單提交后自動聚焦下一個字段
document.querySelectorAll('input').forEach(input => {
input.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
const next = this.nextElementSibling;
if (next && (next.tagName === 'INPUT' || next.tagName === 'TEXTAREA')) {
next.focus();
}
}
});
});
/* 不要移除默認的outline,而是美化它 */
:focus {
outline: 2px solid #4a90e2;
outline-offset: 2px;
}
<label for="search">搜索內容:</label>
<input id="search" type="text" aria-describedby="search-help">
<span id="search-help">請輸入至少3個字符</span>
// 動態添加元素后設置焦點
function addNewItem() {
const list = document.getElementById('list');
const newItem = document.createElement('li');
newItem.innerHTML = `<input type="text" class="new-item">`;
list.appendChild(newItem);
setTimeout(() => {
newItem.querySelector('input').focus();
}, 0);
}
document.getElementById('email').addEventListener('blur', function() {
if (!this.value.includes('@')) {
this.setCustomValidity('請輸入有效的電子郵件地址');
this.reportValidity();
this.focus();
} else {
this.setCustomValidity('');
}
});
區分鼠標點擊和鍵盤操作產生的焦點:
document.addEventListener('focus', (e) => {
if (e.target.matches(':focus-visible')) {
// 鍵盤操作產生的焦點
e.target.classList.add('keyboard-focus');
}
}, true);
通過合理使用JavaScript焦點管理技術,可以顯著提升Web應用的可訪問性和用戶體驗。 “`
(注:實際字數約1500字,此處為精簡展示核心內容的結構化版本)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。