aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/window/hashchange_event/index.html
blob: de51f52ff87d44521e26d42a529686be0ac2ee6f (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
---
title: 'Window: hashchange event'
slug: Web/API/Window/hashchange_event
tags:
  - API
  - DOM
  - Event
  - HashChange
  - Window
  - onhashchange
  - 事件
  - 参考
translation_of: Web/API/Window/hashchange_event
---
<p>{{APIRef}}</p>

<p>当URL的片段标识符更改时,将触发<strong>hashchange</strong>事件 (跟在#符号后面的URL部分,包括#符号)</p>

<table class="properties">
 <tbody>
  <tr>
   <th scope="row">Bubbles</th>
   <td>Yes</td>
  </tr>
  <tr>
   <th scope="row">Cancelable</th>
   <td>No</td>
  </tr>
  <tr>
   <th scope="row">Interface</th>
   <td>{{domxref("HashChangeEvent")}}</td>
  </tr>
  <tr>
   <th scope="row">Event handler</th>
   <td>{{domxref("WindowEventHandlers/onhashchange", "onhashchange")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="示例">示例</h2>

<p>你可以在 {{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 <code>hashchange</code> 事件:</p>

<pre class="brush:js">window.addEventListener('hashchange', function() {
  console.log('The hash has changed!')
}, false);</pre>

<p>或使用 <code>onhashchange</code> 事件处理程序属性:</p>

<pre class="brush: js">function locationHashChanged() {
  if (location.hash === '#cool-feature') {
    console.log("You're visiting a cool feature!");
  }
}

window.onhashchange = locationHashChanged;</pre>

<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('HTML WHATWG', 'indices.html#event-hashchange', 'hashchange')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>



<p>{{Compat("api.Window.hashchange_event")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li>{{domxref("Window/popstate_event", "popstate")}}</li>
 <li>{{domxref("WindowEventHandlers.onhashchange")}}</li>
</ul>