Element:focus 事件
當元素獲得焦點時,會觸發 focus 事件。該事件不會冒泡,但緊隨其後的相關 focusin 事件會冒泡。
focus 事件的反向事件是 blur 事件,當元素失去焦點時會觸發該事件。
focus 事件是不可取消的。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("focus", (event) => { })
onfocus = (event) => { }
事件型別
一個 FocusEvent。繼承自 UIEvent 和 Event。
事件屬性
此介面還繼承了其父級 UIEvent 的屬性,以及間接繼承自 Event 的屬性。
-
失去焦點的元素(如果有)。
示例
簡單示例
HTML
html
<form id="form">
<label>
Some text:
<input type="text" placeholder="text input" />
</label>
<label>
Password:
<input type="password" placeholder="password" />
</label>
</form>
JavaScript
js
const password = document.querySelector('input[type="password"]');
password.addEventListener("focus", (event) => {
event.target.style.background = "pink";
});
password.addEventListener("blur", (event) => {
event.target.style.background = "";
});
結果
事件委託
有兩種方法可以實現此事件的事件委託:使用 focusin 事件,或將 addEventListener() 的 useCapture 引數設定為 true。
HTML
html
<form id="form">
<label>
Some text:
<input type="text" placeholder="text input" />
</label>
<label>
Password:
<input type="password" placeholder="password" />
</label>
</form>
JavaScript
js
const form = document.getElementById("form");
form.addEventListener(
"focus",
(event) => {
event.target.style.background = "pink";
},
true,
);
form.addEventListener(
"blur",
(event) => {
event.target.style.background = "";
},
true,
);
結果
規範
| 規範 |
|---|
| UI 事件 # event-type-focus |
| HTML # handler-onfocus |
瀏覽器相容性
載入中…
另見
HTMLElement.focus()方法- 相關事件:
blur、focusin、focusout - 此事件在
Window上的目標:focus事件 - 聚焦:focus/blur