focus 事件


將事件處理常式繫結到「focus」事件,或在元素上觸發該事件。

.on( "focus" [, eventData ], handler )傳回:jQuery

說明:將事件處理常式繫結到「focus」事件。

此頁面說明了 focus 事件。有關已棄用的 .focus() 方法,請參閱 .focus()

  • 當元素獲得焦點時,會傳送 focus 事件給該元素。此事件隱含地適用於一組有限的元素,例如表單元素(<input><select> 等)和連結(<a href>)。在最近的瀏覽器版本中,可以透過明確設定元素的 tabindex 屬性,將事件擴充套件到包括所有元素類型。元素可以透過鍵盤命令(例如 Tab 鍵)或透過滑鼠按一下元素來獲得焦點。
  • 具有焦點的元素通常會以某種方式由瀏覽器加以突顯,例如在元素周圍加上虛線。焦點用於確定哪個元素最先接收與鍵盤相關的事件。

嘗試將焦點設定為隱藏元素會導致 Internet Explorer 中發生錯誤。請注意僅對可見元素使用 .trigger( "focus" )。若要執行元素的焦點事件處理常式,而不將焦點設定為該元素,請使用 .triggerHandler( "focus" ),而不是 .trigger( "focus" )

例如,考慮 HTML

1
2
3
4
5
6
7
<form>
<input id="target" type="text" value="Field 1">
<input type="text" value="Field 2">
</form>
<div id="other">
Trigger the handler
</div>

事件處理常式可以繫結到第一個輸入欄位

1
2
3
$( "#target" ).on( "focus", function() {
alert( "Handler for `focus` called." );
} );

現在按一下第一個欄位,或從另一個欄位切換到第一個欄位,會顯示警示

已呼叫 `focus` 處理常式。

當按一下另一個元素時,我們可以觸發事件

1
2
3
$( "#other" ).on( "click", function() {
$( "#target" ).trigger( "focus" );
} );

此程式碼執行後,按一下 觸發處理常式 也會顯示警示訊息。

focus 事件不會冒泡。從 1.4.2 版開始,jQuery 會透過在其事件委派方法中將 focus 對應到 focusin 事件,來解決此限制。

原生 focus 事件在所有版本的 IE 中都是非同步的,這與其他瀏覽器相反。為了避免與此差異相關的問題,從 jQuery 3.7.0 開始,jQuery 使用 focusin 作為 IE 中 focus 的原生後備事件。

範例

觸發焦點。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
span {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p><input type="text"> <span>focus fire</span></p>
<p><input type="password"> <span>focus fire</span></p>
<script>
$( "input" ).on( "focus", function() {
$( this ).next( "span" ).css( "display", "inline" ).fadeOut( 1000 );
} );
</script>
</body>
</html>

示範

若要阻止人們在文字輸入方塊中輸入,請嘗試

1
2
3
$( "input[type=text]" ).on( "focus", function() {
$( this ).trigger( "blur" );
} );

若要在頁面啟動時將焦點放在 ID 為「login」的登入輸入方塊上,請嘗試

1
2
3
$( function() {
$( "#login" ).trigger( "focus" );
} );