blob: 839557cfef61f6e580472a6c0f0fa178264c0acf (
plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
---
title: 'Window: focus event'
slug: Web/API/Window/focus_event
tags:
- API
- Event
- Focus
translation_of: Web/API/Window/focus_event
---
<div>{{APIRef}}</div>
<p>当元素获得焦点时, <strong><code>focus</code></strong> 事件就会触发。</p>
<p>与 <code>focus</code> 相反的事件是 {{domxref("Window/blur_event", "blur")}}</p>
<table class="properties">
<tbody>
<tr>
</tr>
<tr>
<th>Bubbles(支持冒泡)</th>
<td>No</td>
</tr>
<tr>
<th>Cancelable(可撤销)</th>
<td>No</td>
</tr>
<tr>
<th>Interface(接口)</th>
<td>{{DOMxRef("FocusEvent")}}</td>
</tr>
<tr>
<th>Event handler property(事件处理程序属性)</th>
<td>{{domxref("GlobalEventHandlers/onfocus", "onfocus")}}</td>
</tr>
<tr>
<th>Sync / Async(同步/异步)</th>
<td>Sync</td>
</tr>
<tr>
<th>Composed(可组成)</th>
<td>Yes</td>
</tr>
</tbody>
</table>
<h2 id="示例">示例</h2>
<h3 id="在线示例">在线示例</h3>
<p>本示例在失去焦点时更改文档的外观。它使用 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 监听 <code>focus</code> 和 {{domxref("Window/blur_event", "blur")}} 事件。</p>
<h4 id="HTML">HTML</h4>
<pre class="brush: html"><p id="log">Click on this document to give it focus.</p></pre>
<h4 id="CSS">CSS</h4>
<pre class="brush: css">.paused {
background: #ddd;
color: #555;
}</pre>
<h4 id="JavaScript">JavaScript</h4>
<pre class="brush: js">function pause() {
document.body.classList.add('paused');
log.textContent = 'FOCUS LOST!';
}
function play() {
document.body.classList.remove('paused');
log.textContent = 'This document has focus. Click outside the document to lose focus.';
}
const log = document.getElementById('log');
window.addEventListener('blur', pause);
window.addEventListener('focus', play);</pre>
<h4 id="结果">结果</h4>
<p>{{EmbedLiveSample("Live_example")}}</p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName("UI Events", "#event-type-focus")}}</td>
<td>{{Spec2("UI Events")}}</td>
<td>添加了组成此事件的信息。</td>
</tr>
<tr>
<td>{{SpecName("DOM3 Events", "#event-type-focus")}}</td>
<td>{{Spec2("DOM3 Events")}}</td>
<td>初始定义</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("api.Window.focus_event")}}</p>
<h2 id="参考">参考</h2>
<ul>
<li>相关联事件: {{domxref("Window/blur_event", "blur")}}</li>
<li><code>Element</code> 目标上的这个事件: {{domxref("Element/focus_event", "focus")}} 事件</li>
</ul>
|