blob: f4e98d96467a41bf92effa24571df255c55e6311 (
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
|
---
title: EventListener
slug: Web/API/EventListener
tags:
- API
- DOM
- DOM Events
- 事件
translation_of: Web/API/EventListener
---
<p>{{APIRef("DOM Events")}}</p>
<p><strong><code>EventListener</code></strong> 接口表示的对象可以处理 {{domxref("EventTarget")}} 对象所调度的事件。</p>
<div class="note">
<p><strong>Note:</strong> 由于需要与以前遗留的内容进行兼容,<code>EventListener</code> 可以接受一个函数,也可以接受带有 <code>handleEvent()</code> 函数属性的对象。这将在下面的<a href="#Example">例子</a>中展现出来。</p>
</div>
<h2 id="属性">属性</h2>
<p><em>此接口未实现或继承任何属性。</em></p>
<h2 id="方法">方法</h2>
<p><em>此接口未继承任何方法。</em></p>
<dl>
<dt>{{domxref("EventListener.handleEvent()")}}</dt>
<dd>一个在特定类型的事件被调用时运行的函数。</dd>
</dl>
<h2 id="例子">例子</h2>
<h3 id="HTML">HTML</h3>
<pre class="brush: html"><button id="btn">点这里!</button></pre>
<h3 id="JavaScript">JavaScript</h3>
<pre class="brush: js">const buttonElement = document.getElementById('btn');
// Add a handler for the 'click' event by providing a callback function.
// Whenever the element is clicked, a pop-up with "Element clicked!" will
// appear.
buttonElement.addEventListener('click', function (event) {
alert('Element clicked through function!');
});
// 由于兼容性原因,一个带有 handleEvent 函数属性的对象也可以达到相同的效果。
buttonElement.addEventListener('click', {
handleEvent: function (event) {
alert('Element clicked through handleEvent property!');
}
});
</pre>
<h3 id="结果">结果</h3>
<p>{{EmbedLiveSample('Example')}}</p>
<h3 id="参见:">参见:</h3>
<ul>
<li><a href="/zh-CN/docs/Web/API/EventTarget/addEventListener">addEventListener</a></li>
</ul>
<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('DOM WHATWG', '#callbackdef-eventlistener', 'EventListener')}}</td>
<td>{{Spec2('DOM WHATWG')}}</td>
<td>No change.</td>
</tr>
<tr>
<td>{{SpecName('DOM2 Events', '#Events-EventListener', 'EventListener')}}</td>
<td>{{Spec2('DOM2 Events')}}</td>
<td>Initial definition.</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("api.EventListener")}}</p>
|