diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 12:56:40 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 12:56:40 +0100 |
commit | 310fd066e91f454b990372ffa30e803cc8120975 (patch) | |
tree | d5d900deb656a5da18e0b60d00f0db73f3a2e88e /files/zh-cn/web/api/window | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-310fd066e91f454b990372ffa30e803cc8120975.tar.gz translated-content-310fd066e91f454b990372ffa30e803cc8120975.tar.bz2 translated-content-310fd066e91f454b990372ffa30e803cc8120975.zip |
unslug zh-cn: move
Diffstat (limited to 'files/zh-cn/web/api/window')
21 files changed, 981 insertions, 1809 deletions
diff --git a/files/zh-cn/web/api/window/afterprint_event/index.html b/files/zh-cn/web/api/window/afterprint_event/index.html new file mode 100644 index 0000000000..3ee72441cd --- /dev/null +++ b/files/zh-cn/web/api/window/afterprint_event/index.html @@ -0,0 +1,102 @@ +--- +title: afterprint +slug: Web/Events/afterprint +translation_of: Web/API/Window/afterprint_event +--- +<p>在相关联的文档已开始打印或打印预览已关闭之后, 触发 <code>afterprint</code>事件。</p> + +<h2 id="基本信息">基本信息</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="https://html.spec.whatwg.org/multipage/webappapis.html#printing">HTML5</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">DefaultView (<code><window></code>)</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">None</dd> +</dl> + +<h2 id="属性">属性</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event normally bubbles or not.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event is cancellable or not.</td> + </tr> + </tbody> +</table> + +<h2 id="例子">例子</h2> + +<p>使用 <code>addEventListener()</code>:</p> + +<pre class="brush: js notranslate">window.addEventListener('afterprint', (event) => { + console.log('After print'); +});</pre> + +<p>使用 <code>onafterprint</code> 时间监听属性:</p> + +<pre class="brush: js notranslate">window.onafterprint = (event) => { + console.log('After print'); +};</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + </thead> + <tbody> + <tr> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#event-afterprint')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Window.afterprint_event")}}</p> + +<h2 id="相关事件">相关事件</h2> + +<ul> + <li><a href="https://developer.mozilla.org/zh-CN/docs/Web/Events/beforeprint">beforeprint</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/beforeprint_event/index.html b/files/zh-cn/web/api/window/beforeprint_event/index.html new file mode 100644 index 0000000000..fe9480238a --- /dev/null +++ b/files/zh-cn/web/api/window/beforeprint_event/index.html @@ -0,0 +1,100 @@ +--- +title: beforeprint +slug: Web/Events/beforeprint +translation_of: Web/API/Window/beforeprint_event +--- +<p>当相关联的文档即将打印或预览以进行打印时,将触发beforeprint事件。</p> + +<h2 id="基本信息">基本信息</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Specification</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="https://html.spec.whatwg.org/multipage/webappapis.html#printing">HTML5</a></dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelable</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">Target</dt> + <dd style="margin: 0 0 0 120px;">DefaultView (<code><window></code>)</dd> + <dt style="float: left; text-align: right; width: 120px;">Default Action</dt> + <dd style="margin: 0 0 0 120px;">None</dd> +</dl> + +<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><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>事件目标 (DOM 树中的最顶层目标)</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>时间类型</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>事件是否冒泡</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>事件是否可取消</td> + </tr> + </tbody> +</table> + +<h2 id="样例">样例</h2> + +<p>使用 <code>addEventListener()</code>:</p> + +<pre class="brush: js notranslate">window.addEventListener('beforeprint', (event) => { + console.log('Before print'); +});</pre> + +<p>使用 <code>onbeforeprint</code> 事件监听属性:</p> + +<pre class="brush: js notranslate">window.onbeforeprint = (event) => { + console.log('Before print'); +};</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#event-beforeprint')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Window.beforeprint_event")}}</p> + +<h2 id="相关事件">相关事件</h2> + +<ul> + <li><a href="https://developer.mozilla.org/zh-CN/docs/Web/Events/afterprint">afterprint</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/beforeunload_event/index.html b/files/zh-cn/web/api/window/beforeunload_event/index.html new file mode 100644 index 0000000000..9cef2f2cfc --- /dev/null +++ b/files/zh-cn/web/api/window/beforeunload_event/index.html @@ -0,0 +1,104 @@ +--- +title: 'Window: beforeunload event' +slug: Web/Events/beforeunload +tags: + - Event + - Window + - beforeunload + - 事件 + - 参考 +translation_of: Web/API/Window/beforeunload_event +--- +<p><span style="font-family: consolas,monaco,andale mono,monospace;">当浏览器窗口关闭或者刷新时,会触发beforeunload事件。当前页面不会直接关闭,可以点击确定按钮关闭或刷新,也可以取消关闭或刷新。</span></p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Bubbles</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Cancelable</th> + <td>Yes</td> + </tr> + <tr> + <th scope="row">Interface</th> + <td>{{domxref("Event")}}</td> + </tr> + <tr> + <th scope="row">Event handler property</th> + <td>{{domxref("WindowEventHandlers/onbeforeunload", "onbeforeunload")}}</td> + </tr> + </tbody> +</table> + +<p>事件使网页能够触发一个确认对话框,询问用户是否真的要离开该页面。如果用户确认,浏览器将导航到新页面,否则导航将会取消。</p> + +<p>根据规范,要显示确认对话框,事件处理程序需要在事件上调用{{domxref("Event.preventDefault()", "preventDefault()")}}。</p> + +<p>但是请注意,并非所有浏览器都支持此方法,而有些浏览器需要事件处理程序实现两个遗留方法中的一个作为代替:</p> + +<ul> + <li>将字符串分配给事件的<code>returnValue</code>属性</li> + <li> + <p>从事件处理程序返回一个字符串。</p> + </li> +</ul> + +<p><span>某些浏览器过去在确认对话框中显示返回的字符串,从而使事件处理程序能够向用户显示自定义消息。但是,此方法已被弃用,并且在大多数浏览器中不再支持。</span></p> + +<p>为避免意外弹出窗口,除非页面已与之交互,否则浏览器可能不会显示在<code>beforeunload</code>事件中创建的提示,甚至根本不会显示它们。</p> + +<p>将事件处理程序/监听器加到<code>window</code>或 <code>document</code>的<code>beforeunload</code>事件后,将阻止浏览器使用内存中的页面导航缓存,例如<a href="https://wiki.developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching">Firefox的Back-Forward缓存</a>或<a href="https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/">WebKit的Page Cache</a>。</p> + +<p>HTML规范指出在此事件中调用{{domxref("window.alert()")}},{{domxref("window.confirm()")}}以及{{domxref("window.prompt()")}}方法,可能会失效。更多详细信息,请参见<a href="https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#user-prompts">HTML规范</a>。</p> + +<h2 id="示例">示例</h2> + +<p>HTML规范指出作者应该使用 {{domxref("Event.preventDefault()")}} 而非 {{domxref("Event.returnValue")}},然而,不是所有浏览器都支持这么做。</p> + +<pre class="brush: js notranslate">window.addEventListener('beforeunload', (event) => { + // Cancel the event as stated by the standard. + event.preventDefault(); + // Chrome requires returnValue to be set. + event.returnValue = ''; +}); +</pre> + +<h2 id="规范">规范</h2> + +<table> + <thead> + <tr> + <th scope="col"><strong>规范</strong></th> + <th scope="col"><strong>状态</strong></th> + <th scope="col">注释</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "indices.html#event-beforeunload", "beforeunload")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C", "browsers.html#unloading-documents", "beforeunload")}}</td> + <td>{{Spec2("HTML5 W3C")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div class="hidden">此页面上的兼容性表是根据结构化数据生成的。 如果您想贡献数据,请查看 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 并向我们发送请求请求。</div> + +<p>{{Compat("api.Window.beforeunload_event")}}</p> + +<h2 id="参阅">参阅</h2> + +<ul> + <li>相关事件:{{domxref("Window/DOMContentLoaded_event", "DOMContentLoaded")}}, {{domxref("Document/readystatechange_event", "readystatechange")}}, {{domxref("Window/load_event", "load")}}, {{domxref("Window/unload_event", "unload")}}</li> + <li><a href="https://html.spec.whatwg.org/#prompt-to-unload-a-document">Unloading Documents — Prompt to unload a document</a></li> + <li><a href="https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs">Remove Custom Messages in onbeforeload Dialogs after Chrome 51</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/window.blur()/index.html b/files/zh-cn/web/api/window/blur/index.html index 0aebdbb367..0aebdbb367 100644 --- a/files/zh-cn/web/api/window/window.blur()/index.html +++ b/files/zh-cn/web/api/window/blur/index.html diff --git a/files/zh-cn/web/api/window/clearinterval/index.html b/files/zh-cn/web/api/window/clearinterval/index.html deleted file mode 100644 index 9a2d6e1790..0000000000 --- a/files/zh-cn/web/api/window/clearinterval/index.html +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: WindowTimers.clearInterval() -slug: Web/API/Window/clearInterval -tags: - - API - - WindowOrWorkerGlobalScope - - 参考 - - 方法 -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval ---- -<div>{{ApiRef("HTML DOM")}}</div> - -<p>{{domxref("WindowOrWorkerGlobalScope")}} mixin 的 <strong><code>clearInterval()</code></strong> 方法可取消先前通过 {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 设置的重复定时任务。</p> - -<h2 id="语法">语法</h2> - -<pre class="syntaxbox"><em>scope</em>.clearInterval(<var>intervalID</var>) -</pre> - -<h3 id="Parameters">Parameters</h3> - -<dl> - <dt><code>intervalID</code></dt> - <dd>要取消的定时器的 ID。是由 <code>setInterval()</code> 返回的。</dd> -</dl> - -<p>值得一提的是,{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 和 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} 共用其定义的 IDs,即可以使用 <code>clearInterval()</code> 和 {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} 中的任意一个。然而,为了使代码可读性更强,你应该尽量避免这种用法。</p> - -<h3 id="返回值">返回值</h3> - -<p>{{jsxref("undefined")}}</p> - -<h2 id="示例">示例</h2> - -<p>查看 <a href="/en-US/docs/DOM/window.setInterval#Example"><code>setInterval()</code> 的示例</a>。</p> - -<h2 id="Specification" name="Specification">规范</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">规范</th> - <th scope="col">状态</th> - <th scope="col">备注</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}</td> - <td>{{Spec2("HTML WHATWG")}}</td> - <td>Method moved to the <code>WindowOrWorkerGlobalScope</code> mixin in the latest spec.</td> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td></td> - </tr> - </tbody> -</table> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - - - -<p>{{Compat("api.WindowOrWorkerGlobalScope.clearInterval")}}</p> - -<h2 id="参见">参见</h2> - -<ul> - <li><a href="/en-US/docs/JavaScript/Timers" title="JavaScript/Timers">JavaScript 定时器</a></li> - <li>{{domxref("WindowOrWorkerGlobalScope.setTimeout")}}</li> - <li>{{domxref("WindowOrWorkerGlobalScope.setInterval")}}</li> - <li>{{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}</li> - <li>{{domxref("Window.requestAnimationFrame")}}</li> - <li><a href="/en-US/docs/JavaScript/Timers/Daemons" title="JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li> -</ul> diff --git a/files/zh-cn/web/api/window/domcontentloaded_event/index.html b/files/zh-cn/web/api/window/domcontentloaded_event/index.html new file mode 100644 index 0000000000..67c6a44253 --- /dev/null +++ b/files/zh-cn/web/api/window/domcontentloaded_event/index.html @@ -0,0 +1,128 @@ +--- +title: DOMContentLoaded +slug: Web/Events/DOMContentLoaded +tags: + - DOMContentLoaded + - Window.open() + - load + - window.onload +translation_of: Web/API/Window/DOMContentLoaded_event +--- +<p>当初始的 <strong>HTML </strong>文档被完全加载和解析完成之后,<strong><code>DOMContentLoaded</code> </strong>事件被触发,而无需等待样式表、图像和子框架的完全加载。</p> + +<p>模拟的css文件:CSS.php</p> + +<pre class="notranslate"><?php +sleep(3);</pre> + +<p>测试代码:</p> + +<pre class="notranslate"><link rel="stylesheet" href="css.php"> +<script> +document.addEventListener('DOMContentLoaded',function(){ + console.log('3 seconds passed'); +}); +</script></pre> + +<p>如果将link置于script之后,就会立即打印。</p> + +<p>{{Note("同步 JavaScript 会暂停 DOM 的解析。")}}</p> + +<p>{{Note("还有许多通用和独立的库提供跨浏览器方法来检测 DOM 是否已准备就绪")}}</p> + +<h2 id="加速中">加速中</h2> + +<p>如果您希望 DOM 在用户请求页面后尽可能快地解析,你可以做的一些事情是把你的 <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests">JavaScript 异步化</a> 以及 <a href="https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery">优化样式表的加载</a>, 由于被并行加载而减慢页面加载,从主 html 文档“窃取”流量。</p> + +<h2 id="常规信息">常规信息</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">规范</dt> + <dd style="margin: 0pt 0pt 0pt 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#the-end">HTML5</a></dd> + <dt style="float: left; text-align: right; width: 120px;">接口</dt> + <dd style="margin: 0pt 0pt 0pt 120px;">Event</dd> + <dt style="float: left; text-align: right; width: 120px;">是否冒泡</dt> + <dd style="margin: 0pt 0pt 0pt 120px;">是</dd> + <dt style="float: left; text-align: right; width: 120px;">能否取消</dt> + <dd style="margin: 0pt 0pt 0pt 120px;">能 (尽管一个简单的事件被指定为不可取消)</dd> + <dt style="float: left; text-align: right; width: 120px;">目标</dt> + <dd style="margin: 0pt 0pt 0pt 120px;">Document</dd> + <dt style="float: left; text-align: right; width: 120px;">默认行为</dt> + <dd style="margin: 0pt 0pt 0pt 120px;">无.</dd> +</dl> + +<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><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>产生该事件的对象(DOM树中最顶级的那个对象).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>事件类型.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>该事件是否冒泡.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>该事件是否可取消默认行为.</td> + </tr> + </tbody> +</table> + +<h2 id="示例" style="margin-bottom: 20px; font-size: 28px; line-height: 28px;">示例</h2> + +<pre class="notranslate"><code><script> + document.addEventListener("DOMContentLoaded", function(event) { + console.log("DOM fully loaded and parsed"); + }); +</script></code></pre> + +<pre class="notranslate"><code><script> + document.addEventListener("DOMContentLoaded", function(event) { + console.log("DOM fully loaded and parsed"); + }); + + for(var i=0; i<1000000000; i++){ + // </code>这个同步脚本将延迟DOM的解析。 + // 所以DOMContentLoaded事件稍后将启动。 +<code> } </code><code> +</script></code></pre> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("api.Window.DOMContentLoaded_event")}}</p> + +<p><span>至少从Gecko 1.9.2,Chrome 6,以及Safari 4开始,就已经实现了</span><span>该事件的</span><span>冒泡行为.</span></p> + +<h3 id="兼容不支持该事件的浏览器">兼容不支持该事件的浏览器</h3> + +<p>在IE8中,可以使用<code>readystatechange</code>事件来检测DOM文档是否加载完毕.在更早的IE版本中,可以通过每隔一段时间执行一次<code>document.documentElement.doScroll("left")来检测这一状态,</code>因为这条代码在DOM加载完毕之前执行时会抛出错误(throw an error)。</p> + +<p>诸如jQuery这样的通用JS库,会提供跨浏览器的方法来检测DOM是否加载完成。也有其他专门实现该功能的脚本:<a href="https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js" title="https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js">contentloaded.js</a> (只能添一个时间监听函数)以及<a href="https://github.com/addyosmani/jquery.parts/blob/master/jquery.documentReady.js" title="https://github.com/addyosmani/jquery.parts/blob/master/jquery.documentReady.js">jquery.documentReady.js</a> (并不依赖jQuery,虽然名字中有jquery).</p> + +<h2 id="相关事件">相关事件</h2> + +<ul> + <li>{{event("DOMContentLoaded")}}</li> + <li>{{event("readystatechange")}}</li> + <li>{{event("load")}}</li> + <li>{{event("beforeunload")}}</li> + <li>{{event("unload")}}</li> + <li><a href="https://codepen.io/gildata/pen/VrzXOb">DOMContentLoaded demo</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/getattention/index.html b/files/zh-cn/web/api/window/getattention/index.html deleted file mode 100644 index f17531eb18..0000000000 --- a/files/zh-cn/web/api/window/getattention/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Window.getAttention() -slug: Web/API/Window/getAttention -translation_of: Web/API/Window/getAttention ---- -<div>{{ ApiRef() }}</div> - -<p>The <code><strong>Window.getAttention()</strong></code> method attempts to get the user's attention. The mechanism for this happening depends on the specific operating system and window manager.</p> - -<h2 id="语法">语法</h2> - -<pre class="syntaxbox">window.getAttention(); -</pre> - -<h2 id="Notes">Notes</h2> - -<p>On Windows, the taskbar button for the window flashes, if this hasn't been disabled by the user.</p> - -<p>On Linux, the behaviour varies from window manager to window manager - some flash the taskbar button, others focus the window immediately. This may be configurable as well.</p> - -<p>On Macintosh, the icon in the upper right corner of the desktop flashes.</p> - -<p>The function is disabled for web content. Neither Gecko nor Internet Explorer supports this feature now for web content. <code>getAttention</code> will still work when used from <a href="en/Chrome">chrome</a> in a Gecko application.</p> - -<h2 id="Specification">Specification</h2> - -<p>DOM Level 0. Not part of specification.</p> - -<h2 id="Browser_compatibility">Browser compatibility</h2> - - - -<p>{{Compat("api.Window.getAttention")}}</p> diff --git a/files/zh-cn/web/api/window/load_event/index.html b/files/zh-cn/web/api/window/load_event/index.html new file mode 100644 index 0000000000..5cfb7b075f --- /dev/null +++ b/files/zh-cn/web/api/window/load_event/index.html @@ -0,0 +1,161 @@ +--- +title: load +slug: Web/Events/load +tags: + - load +translation_of: Web/API/Window/load_event +--- +<p>{{APIRef}}</p> + +<p>当整个页面及所有依赖资源如样式表和图片都已完成加载时,将触发<code>load</code>事件。</p> + +<p>它与{{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}}不同,后者只要页面DOM加载完成就触发,无需等待依赖资源的加载。</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">是否冒泡</th> + <td>否</td> + </tr> + <tr> + <th scope="row">能否取消</th> + <td>否</td> + </tr> + <tr> + <th scope="row">接口</th> + <td>{{domxref("Event")}}</td> + </tr> + <tr> + <th scope="row">Event handler property</th> + <td>{{domxref("GlobalEventHandlers/onload", "onload")}}</td> + </tr> + </tbody> +</table> + +<h2 id="用法">用法</h2> + +<p>当页面及资源完全加载后在控制台打印一段信息:</p> + +<pre class="brush: js notranslate">window.addEventListener('load', (event) => { + console.log('page is fully loaded'); +});</pre> + +<p>也可以使用<code>onload</code>实现:</p> + +<pre class="brush: js notranslate">window.onload = (event) => { + console.log('page is fully loaded'); +};</pre> + +<h2 id="示例">示例</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><div class="controls"> + <button id="reload" type="button">Reload</button> +</div> + +<div class="event-log"> + <label>Event log:</label> + <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> +</div></pre> + +<div class="hidden"> +<h3 id="CSS">CSS</h3> + +<pre class="brush: css notranslate">body { + display: grid; + grid-template-areas: "control log"; +} + +.controls { + grid-area: control; + display: flex; + align-items: center; + justify-content: center; +} + +.event-log { + grid-area: log; +} + +.event-log-contents { + resize: none; +} + +label, button { + display: block; +} + +#reload { + height: 2rem; +} +</pre> +</div> + +<h3 id="JS">JS</h3> + +<pre class="brush: js notranslate">const log = document.querySelector('.event-log-contents'); +const reload = document.querySelector('#reload'); + +reload.addEventListener('click', () => { + log.textContent =''; + window.setTimeout(() => { + window.location.reload(true); + }, 200); +}); + +window.addEventListener('load', (event) => { + log.textContent = log.textContent + 'load\n'; +}); + +document.addEventListener('readystatechange', (event) => { + log.textContent = log.textContent + `readystate: ${document.readyState}\n`; +}); + +document.addEventListener('DOMContentLoaded', (event) => { + log.textContent = log.textContent + `DOMContentLoaded\n`; +}); + +</pre> + +<h4 id="结果">结果</h4> + +<p>{{ EmbedLiveSample('Live_example', '100%', '160px') }}</p> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('UI Events', '#event-type-load', 'load')}}</td> + <td>{{Spec2('UI Events')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#delay-the-load-event', 'load event')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>此链接指向加载文档结束时执行步骤中的部分。“load”事件也会在许多元素上触发。 请注意,规范中有很多地方涉及到可以"<a href="https://html.spec.whatwg.org/multipage/parsing.html#delay-the-load-event">延迟加载事件</a>"的内容。</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div class="hidden"> +<p>此页面上的兼容性表是根据结构化数据生成的。 如果您想贡献数据,请查看 <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 并向我们发送请求请求。</p> +</div> + +<p>{{Compat("api.Window.load_event")}}</p> + +<h2 id="参阅">参阅</h2> + +<ul> + <li>相关事件: {{domxref("Window/DOMContentLoaded_event", "DOMContentLoaded")}}, {{domxref("Document/readystatechange_event", "readystatechange")}}, {{domxref("Window/beforeunload_event", "beforeunload")}}, {{domxref("Window/unload_event", "unload")}}</li> +</ul> diff --git a/files/zh-cn/web/api/window/onbeforeunload/index.html b/files/zh-cn/web/api/window/onbeforeunload/index.html deleted file mode 100644 index 78bed99eb9..0000000000 --- a/files/zh-cn/web/api/window/onbeforeunload/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: window.onbeforeunload -slug: Web/API/Window/onbeforeunload -translation_of: Web/API/WindowEventHandlers/onbeforeunload ---- -<div>{{ApiRef}}</div> - -<h2 id="Summary" name="Summary">概述</h2> - -<p>当窗口即将被{{domxref("window.onunload","卸载(关闭)")}}时,会触发该事件.此时页面文档依然可见,且该事件的默认动作可以被{{domxref("event.preventDefault","取消")}}.</p> - -<h2 id="Syntax" name="Syntax">语法</h2> - -<pre class="syntaxbox">window.onbeforeunload = <var>funcRef</var></pre> - -<ul> - <li><code>funcRef</code> 是一个函数引用</li> - <li>该函数应当将一个说明字符串赋值给<code>Event</code>对象的<code>returnValue</code>属性(兼容旧版浏览器),并且返回该字符串</li> - <li>请注意,在Firefox4及其后续版本中,返回的说明字符串并不向用户显示,也就是无法自定义说明字符串.查看<a class="external link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=588292" title="https://bugzilla.mozilla.org/show_bug.cgi?id=588292">Bug 588292</a>.</li> -</ul> - -<h2 id="Example" name="Example">示例</h2> - -<pre class="brush:js">window.onbeforeunload = function (e) { - e = e || window.event; - - // 兼容IE8和Firefox 4之前的版本 - if (e) { - e.returnValue = '关闭提示'; - } - - // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+ - return '关闭提示'; -}; -</pre> - -<h2 id="附注">附注</h2> - -<p>当该事件返回的字符串(事前设置好的event.returnValue的值)不为null或者undefined时,弹出确认窗口让用户自行选择是否关闭当前页面。一些浏览器将该事件返回的字符串显示在弹出窗上。从Firefox 4、 Chrome 51、Opera 38 和Safari 9.1开始,通用确认信息代替事件返回的字符串。比如,火狐上会显示“本页面要求您确认您要离开 - 您输入的数据可能不会被保存”,请查阅{{bug("588292")}}和<a href="https://www.chromestatus.com/feature/5349061406228480">Chrome Platform Status</a>。</p> - -<p>从2011年5月25日起, <a class="external" href="http://www.w3.org/TR/html5-diff/#changes-2011-05-25" title="http://www.w3.org/TR/html5-diff/#changes-2011-05-25">HTML5 规范</a> 声明:在该事件的处理函数中调用下列弹窗相关的方法时,可以忽略不执行,<code><a class="new" href="https://developer.mozilla.org/zh-CN/docs/DOM/window.showModalDialog">window.showModalDialog()</a></code>, <code><a href="https://developer.mozilla.org/zh-CN/docs/DOM/window.alert">window.alert()</a></code>, <code><a class="new" href="https://developer.mozilla.org/zh-CN/docs/DOM/window.confirm">window.confirm()</a></code> <code><a href="https://developer.mozilla.org/zh-CN/docs/DOM/window.prompt">window.prompt()</a></code>.</p> - -<p>需要指出的是,许多浏览器会忽略该事件并自动关闭页面无需用户的确认。火狐浏览器在配置页面<a>about:config</a>设有一个dom.disable_beforeunload的开关变量用于开启这个功能。</p> - -<p>你可以通过{{domxref("EventTarget.addEventListener","window.addEventListener()")}} 或者 {{event("beforeunload")}} 创建该事件。更多信息请点击以上链接。</p> - -<p>创建这个事件能防止浏览器缓存部分由javascript产生的页面内容。在页面中含Javascript产生的内容情形下,再次导航返回到原页面javascript不在运行。如果事先有window.onbeforeunload事件,导航返回到先前的页面后javascript将被触发并更新页面内容。</p> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<div>{{CompatibilityTable}}</div> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari (WebKit)</th> - </tr> - <tr> - <td>Basic support</td> - <td>1</td> - <td>1</td> - <td>4</td> - <td>12</td> - <td>3</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Phone</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - <td>{{CompatUnknown}}</td> - </tr> - </tbody> -</table> -</div> - -<h2 id="Specification" name="Specification">规范</h2> - -<p><code>该事件最初是由微软公司的IE4引进,虽然没有公开的规范说明,但所有浏览器都支持该事件.</code>目前已被添加至HTML5规范草案中.</p> - -<ul> - <li>{{spec("http://dev.w3.org/html5/spec-LC/history.html#unloading-documents", "HTML5: Browsing the Web, Unloading documents", "LC")}}</li> -</ul> - -<h2 id="See also" name="See also">相关链接</h2> - -<ul> - <li><a href="http://msdn.microsoft.com/zh-CN/library/ms536907(VS.85).aspx">MSDN: onbeforeunload event</a></li> -</ul> diff --git a/files/zh-cn/web/api/window/onhashchange/index.html b/files/zh-cn/web/api/window/onhashchange/index.html deleted file mode 100644 index 0c7f3ebefa..0000000000 --- a/files/zh-cn/web/api/window/onhashchange/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: window.onhashchange -slug: Web/API/Window/onhashchange -tags: - - HTML-DOM - - Property - - Reference - - WindowEventHandlers -translation_of: Web/API/WindowEventHandlers/onhashchange ---- -<p>{{APIRef("HTML DOM")}}</p> - -<p>当 一个窗口的 hash (URL 中 # 后面的部分)改变时就会触发 <strong>hashchange </strong>事件(参见 {{domxref("Window.location", "location.hash")}})。</p> - -<h2 class="editable" id="语法"><span>语法</span></h2> - -<pre class="syntaxbox">window.onhashchange = funcRef; -</pre> - -<p>或者</p> - -<pre class="syntaxbox"><body onhashchange="funcRef();"></pre> - -<p>以上操作将覆盖现有的事件处理程序。</p> - -<p>为了添加一个新的事件处理程序,而不覆盖掉已有的其他事件处理程序,可以使用函数 <strong>"addEventListener"</strong>。</p> - -<pre class="syntaxbox">window.addEventListener("hashchange", funcRef, false); -</pre> - -<h3 id="参数"><span>参数</span></h3> - -<dl> - <dt><code>funcRef</code></dt> - <dd>对一个函数的引用。</dd> -</dl> - -<h2 id="例子">例子</h2> - -<pre class="brush: js">if ("onhashchange" in window) { - alert("该浏览器支持 hashchange 事件!"); -} - -function locationHashChanged() { - if (location.hash === "#somecoolfeature") { - somecoolfeature(); - } -} - -window.onhashchange = locationHashChanged; -</pre> - -<h2 class="editable" id="hashchange_事件">hashchange 事件</h2> - -<p><code>hashchange</code> 事件对象有下面两个属性:</p> - -<table class="standard-table"> - <tbody> - <tr> - <td class="header">属性</td> - <td class="header">类型</td> - <td class="header">描述</td> - </tr> - <tr> - <td><code>newURL</code> {{ gecko_minversion_inline("6.0") }}</td> - <td><code>DOMString</code></td> - <td>当前页面新的URL</td> - </tr> - <tr> - <td><code>oldURL</code> {{ gecko_minversion_inline("6.0") }}</td> - <td><code>DOMString</code></td> - <td>当前页面旧的URL</td> - </tr> - </tbody> -</table> - -<h3 id="Workaround_for_event.newURL_and_event.oldURL">Workaround for event.newURL and event.oldURL</h3> - -<pre class="brush: js">//let this snippet run before your hashchange event binding code -if(!window.HashChangeEvent)(function(){ - var lastURL=document.URL; - window.addEventListener("hashchange",function(event){ - Object.defineProperty(event,"oldURL",{enumerable:true,configurable:true,value:lastURL}); - Object.defineProperty(event,"newURL",{enumerable:true,configurable:true,value:document.URL}); - lastURL=document.URL; - }); -}());</pre> - -<h2 id="规范">规范</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> - <td>{{Spec2('HTML WHATWG')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}</td> - <td>{{Spec2('HTML5.1')}}</td> - <td> </td> - </tr> - <tr> - <td>{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}</td> - <td>{{Spec2('HTML5 W3C')}}</td> - <td> </td> - </tr> - </tbody> -</table> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<p>{{Compat("api.WindowEventHandlers.onhashchange")}}</p> - -<ul> - <li><a href="/en-US/docs/DOM/Manipulating_the_browser_history" title="DOM/Manipulating the browser history">Manipulating the browser history</a>, <a href="/en-US/docs/DOM/window.history" title="DOM/window.history">history.pushState() and history.replaceState()</a> methods, <a href="/en-US/docs/DOM/window.onpopstate" title="DOM/window.onpopstate">popstate</a> event.</li> -</ul> diff --git a/files/zh-cn/web/api/window/onmouseup/index.html b/files/zh-cn/web/api/window/onmouseup/index.html deleted file mode 100644 index 03a4b116b8..0000000000 --- a/files/zh-cn/web/api/window/onmouseup/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: window.onmouseup -slug: Web/API/Window/onmouseup -translation_of: Web/API/GlobalEventHandlers/onmouseup -translation_of_original: Web/API/Window/onmouseup ---- -<p>{{ ApiRef() }}</p> -<h3 id="Summary" name="Summary">概述</h3> -<p>当前窗口的mouseup事件的事件句柄.</p> -<h3 id="Syntax" name="Syntax">语法</h3> -<pre class="eval">window.onmouseup = <em>funcRef</em>; -</pre> -<h3 id="Parameters" name="Parameters">参数</h3> -<ul> - <li><code>funcRef</code> 是个函数引用</li> -</ul> -<h3 id="Example" name="Example">例子</h3> -<pre>window.onmouseup = doFunc; -</pre> -<pre><html> -<head> - -<title>onmouseup测试</title> - -<script type="text/javascript"> - -window.onmouseup = mouseup; - -function mouseup() -{ - alert("检测到mouseup事件!"); -} -</script> -</head> - -<body> -<p>在页面上按下鼠标中某个键,保持几秒后松开.mouseup事件会在你松开鼠标时触发</p> -</body> -</html> -</pre> -<h3 id="Specification" name="Specification">规范</h3> -<p>没有任何公开的标准</p> -<p>{{ languages( { "ja": "ja/DOM/window.onmouseup" ,"en": "en/DOM/window.onmouseup" } ) }}</p> diff --git a/files/zh-cn/web/api/window/onpopstate/index.html b/files/zh-cn/web/api/window/onpopstate/index.html deleted file mode 100644 index 6efc1ec835..0000000000 --- a/files/zh-cn/web/api/window/onpopstate/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: window.onpopstate -slug: Web/API/Window/onpopstate -translation_of: Web/API/WindowEventHandlers/onpopstate ---- -<p>{{ ApiRef() }}</p> - -<p>{{ gecko_minversion_header("2") }}</p> - -<h3 id="Summary" name="Summary">概述</h3> - -<p><code>window.onpopstate</code>是<code>popstate</code>事件在window对象上的事件处理程序.</p> - -<p><code>每当处于激活状态的历史记录条目发生变化时,popstate</code>事件就会在<code>对应window</code>对象上触发. 如果当前<code>处于激活状态的历史记录条目是由</code><code>history.pushState()</code>方法创建,或者由<code>history.replaceState()方法修改过</code>的, 则<code>popstate事件对象的</code><code>state</code>属性包含了这个历史记录条目的state对象的一个拷贝.</p> - -<p><strong>注意:</strong>调用<code>history.pushState()</code>或者<code>history.replaceState()</code>不会触发popstate事件. <code>popstate</code>事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用<code>history.back()、history.forward()、history.go()</code>方法),此外,a 标签的锚点也会触发该事件.</p> - -<p>当网页加载时,各浏览器对<code>popstate</code>事件是否触发有不同的表现,Chrome 和 Safari会触发<code>popstate</code>事件, 而Firefox不会.</p> - -<h3 id="Syntax" name="Syntax">语法</h3> - -<pre class="eval notranslate">window.onpopstate = <em>funcRef</em>; -</pre> - -<ul> - <li><code>funcRef</code> 是个函数名.</li> -</ul> - -<h3 id="popstate事件">popstate事件</h3> - -<p>假如当前网页地址为http://example.com/example.html,则运行下述代码后:</p> - -<pre class="brush: js notranslate">window.onpopstate = function(event) { - alert("location: " + document.location + ", state: " + JSON.stringify(event.state)); -}; -//绑定事件处理函数. -history.pushState({page: 1}, "title 1", "?page=1"); //添加并激活一个历史记录条目 http://example.com/example.html?page=1,条目索引为1 -history.pushState({page: 2}, "title 2", "?page=2"); //添加并激活一个历史记录条目 http://example.com/example.html?page=2,条目索引为2 -history.replaceState({page: 3}, "title 3", "?page=3"); //修改当前激活的历史记录条目 http://ex..?page=2 变为 http://ex..?page=3,条目索引为3 -history.back(); // 弹出 "location: http://example.com/example.html?page=1, state: {"page":1}" -history.back(); // 弹出 "location: http://example.com/example.html, state: null -history.go(2); // 弹出 "location: http://example.com/example.html?page=3, state: {"page":3} -</pre> - -<p>即便进入了那些非pushState和replaceState方法作用过的(比如http://example.com/example.html)没有state对象关联的那些网页, <code>popstate</code>事件也仍然会被触发.</p> - -<h3 id="Specification" name="Specification">规范</h3> - -<ul> - <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#handler-window-onpopstate" title="http://www.whatwg.org/specs/web-apps/current-work/#handler-window-onpopstate">HTML5 popstate event</a></li> -</ul> - -<h3 id="浏览器兼容性">浏览器兼容性</h3> - -<div class="hidden"> -<p>本页面的兼容性表格是由结构化数据生成的。如果你愿意为这些数据做点贡献,请在 github <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> 检出代码,然后发送 pull request 给我们。</p> -</div> - -<p>{{Compat("api.WindowEventHandlers.onpopstate")}}</p> - -<h3 id="相关链接">相关链接</h3> - -<ul> - <li>{{ domxref("window.history") }}</li> - <li><a href="/zh-cn/DOM/Manipulating_the_browser_history" title="zh-cn/DOM/Manipulating the browser history">Manipulating the browser history</a></li> -</ul> - -<p>{{ languages( {"en": "en/DOM/window.onpopstate" } ) }}</p> diff --git a/files/zh-cn/web/api/window/onscroll/index.html b/files/zh-cn/web/api/window/onscroll/index.html deleted file mode 100644 index af48e1575f..0000000000 --- a/files/zh-cn/web/api/window/onscroll/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: window.onscroll -slug: Web/API/Window/onscroll -translation_of: Web/API/GlobalEventHandlers/onscroll -translation_of_original: Web/API/Window/onscroll ---- -<p>{{ ApiRef() }}</p> -<h3 id="Summary" name="Summary">概述</h3> -<p>为当前页面的页面滚动事件添加事件处理函数.</p> -<h3 id="Syntax" name="Syntax">语法</h3> -<pre class="eval">window.onscroll = <em>funcRef</em>; -</pre> -<ul> - <li><code>funcRef</code> 是个函数类型的对象引用或者匿名函数.</li> -</ul> -<h3 id="Example" name="Example">例子</h3> -<pre class="brush: js">window.onscroll = function (e) { - // 当页面的滚动条滚动时,会执行这里的代码 -} -</pre> -<pre class="brush: html"><html> -<head> - -<title>onscroll test</title> - -<script type="text/javascript"> - -window.onscroll = scroll; - -function scroll() -{ - alert("检测到页面滚动事件:"+window.pageXOffset+" "+window.pageYOffset); - // 注意: window.innerWidth 和 window.innerHeight 可以获得页面可见区域的宽和高. -} -</script> -</head> - -<body> -<p>Resize the window</p> -<p>to a very small size,</p> -<p>and use the scrollbars</p> -<p>to move around the page content</p> -<p>in the window.</p> -</body> -</html> -</pre> -<h3 id="Notes" name="Notes">备注</h3> -<p>{{ Bug("189308") }}, 在旧版本的Gecko中(Gecko 1.8/Firefox 1.5之前), scroll 事件只会在用户拖动滚动条时发生,使用方向键和鼠标滚轮滚动页面则不会触发该事件.</p> -<p>当 window.scrollX/scrollY 不为 0时,意味着用户或者网页脚本已经执行了窗口的滚动行为.</p> -<h3 id="Specification" name="Specification">规范</h3> -<ul> - <li><a class="external" href="http://www.w3.org/TR/html5/webappapis.html#event-handlers-on-elements-document-objects-and-window-objects" title="http://www.w3.org/TR/html5/webappapis.html#event-handlers-on-elements-document-objects-and-window-objects">HTML5: Event handlers on elements, Document objects, and Window objects</a></li> -</ul> -<p>{{ languages( { "en": "en/DOM/window.onscroll"} ) }}</p> diff --git a/files/zh-cn/web/api/window/onunload/index.html b/files/zh-cn/web/api/window/onunload/index.html deleted file mode 100644 index 5e766c1d67..0000000000 --- a/files/zh-cn/web/api/window/onunload/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: window.onunload -slug: Web/API/Window/onunload -translation_of: Web/API/WindowEventHandlers/onunload ---- -<p>{{ ApiRef("HTML DOM") }}</p> - -<h3 id="Summary" name="Summary">概述</h3> - -<p>{{domxref("WindowEventHandlers")}} 的混入特性 <strong><code>onunload</code></strong> 是 {{domxref("EventHandler")}} 处理 {{Event("unload")}} 事件的方法。该事件在关闭窗口资源和内容的时候触发。页面资源的清除工作会在 <code>unload</code> 事件之后进行。</p> - -<div class="blockIndicator note"> -<p><strong>注意事项:</strong> 具备弹窗阻止功能的浏览器会忽略 <code>onunload</code> 事件回调中调用的 {{domxref("Window.open()")}} 方法。</p> -</div> - -<div class="blockIndicator warning"> -<p><code>onunload</code> 特性(乃至 <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Window/unload_event">unload</a></code> 事件本身) 并非使用 <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">sendBeacon()</a></code>的正确途径,要调用 <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon">sendBeacon()</a></code> 接口,应当使用 <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event">visibilitychange</a></code> 和 <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event">pagehide</a></code> 事件。 参见 <a href="https://volument.com/blog/sendbeacon-is-broken#comments">Beacon API is broken</a>。</p> -</div> - -<h3 id="Syntax" name="Syntax">语法</h3> - -<pre class="notranslate">window.addEventListener("unload", function(event) { ... }); -window.onunload = function(event) { ... };</pre> - -<p>通常而言,我们推荐使用 {{domxref("EventTarget.addEventListener", "window.addEventListener()")}} 来监听 {{event("unload")}} 事件,而不是直接给 <code>onunload</code> 赋值。</p> - -<h3 id="Example" name="Example">例子</h3> - -<pre class="notranslate"><html> -<head> - -<title>onunload test</title> - -<script type="text/javascript"> - -window.onunload = unloadPage; - -function unloadPage() -{ - alert("unload event detected!"); -} -</script> -</head> - -<body> -<p>Reload a new page into the browser<br /> - to fire the unload event for this page.</p> -<p>You can also use the back or forward buttons<br /> - to load a new page and fire this event.</p> -</body> -</html> - -</pre> - -<h3 id="Specification" name="Specification">规范</h3> - -<p>{{ DOM0() }}</p> - -<p>{{ languages( {"en": "en/DOM/window.onunload" } ) }}</p> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<div class="hidden"> -<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> -</div> - -<p>{{Compat("api.WindowEventHandlers.onunload")}}</p> - -<p>在 Firefox 1.5 中,页面使用此事件处理程序会阻止浏览器在 bfcache 内存中缓存页面(译者注:翻译可能没有达意,请对照英文原文)。详细信息<a href="https://developer.mozilla.org/en-US/Firefox/Releases/1.5/Using_Firefox_1.5_caching">请参阅使用 Firefox 1.5:缓存</a>。</p> diff --git a/files/zh-cn/web/api/window/pageshow_event/index.html b/files/zh-cn/web/api/window/pageshow_event/index.html new file mode 100644 index 0000000000..d0aec41716 --- /dev/null +++ b/files/zh-cn/web/api/window/pageshow_event/index.html @@ -0,0 +1,143 @@ +--- +title: pageshow +slug: Web/Events/pageshow +translation_of: Web/API/Window/pageshow_event +--- +<p>当一条会话历史记录被执行的时候将会触发页面显示(pageshow)事件。(这包括了后退/前进按钮操作,同时也会在onload 事件触发后初始化页面时触发)</p> + +<h2 id="基本信息">基本信息</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">规范</dt> + <dd style="margin: 0 0 0 120px;"><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pageshow">HTML5</a></dd> + <dt style="float: left; text-align: right; width: 120px;">接口</dt> + <dd style="margin: 0 0 0 120px;"><a href="/en-US/docs/Web/API/PageTransitionEvent">PageTransitionEvent</a></dd> + <dt style="float: left; text-align: right; width: 120px;">事件冒泡</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">事件取消</dt> + <dd style="margin: 0 0 0 120px;">No</dd> + <dt style="float: left; text-align: right; width: 120px;">事件源</dt> + <dd style="margin: 0 0 0 120px;">Document (dispatched on Window)</dd> + <dt style="float: left; text-align: right; width: 120px;">默认操作</dt> + <dd style="margin: 0 0 0 120px;">None</dd> +</dl> + +<h2 id="属性">属性</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Property</th> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event normally bubbles or not.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event is cancellable or not.</td> + </tr> + <tr> + <td><code>persisted</code> {{readonlyInline}}</td> + <td>{{jsxref("boolean")}}</td> + <td>表示网页是否是来自缓存.</td> + </tr> + </tbody> +</table> + +<h2 id="示例">示例</h2> + +<p>以下示例将会在控制台打印由前进/后退按钮以及load事件触发后引起的pageshow事件:</p> + +<pre>window.addEventListener('pageshow', function(event) { + console.log('after , pageshow :',event); +}); + + +window.addEventListener('load', function() { + console.log('before'); +}); +</pre> + + + + + +<p>不规范的写法,你同样可以将这个事件当做一个属性添加到body标签,类似于onload</p> + +<pre><body onload="myonload()" onpageshow="mypageshowcode()"></pre> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{CompatibilityTable()}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("4")}}</td> + <td>{{CompatGeckoDesktop("1.8")}}</td> + <td>11</td> + <td>15</td> + <td>5</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.3</td> + <td>{{CompatUnknown()}}</td> + <td>11</td> + <td>35</td> + <td>5.1</td> + </tr> + </tbody> +</table> + + +</div> + +<h2 id="相关事件">相关事件</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla_event_reference/pagehide"><code>pagehide</code></a></li> + <li><a href="/en-US/docs/Using_Firefox_1.5_caching#pageshow_event">Using Firefox 1.5 caching — pageshow event</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/restore/index.html b/files/zh-cn/web/api/window/restore/index.html deleted file mode 100644 index 140827ddb9..0000000000 --- a/files/zh-cn/web/api/window/restore/index.html +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Window.restore() -slug: Web/API/Window/restore -translation_of: Web/API/Window/moveTo -translation_of_original: Web/API/Window/restore ---- -<p>{{APIRef}}</p> - -<p>这个方法现在已经失效,不过可以使用下面的方法代替:</p> - -<p>{{domxref("window.moveTo")}}({{domxref("window.screenX")}}, {{domxref("window.screenY")}});</p> - -<h2 id="Browser_Compatibility">Browser Compatibility</h2> - - - -<p>{{Compat("api.Window.restore")}}</p> diff --git a/files/zh-cn/web/api/window/setinterval/index.html b/files/zh-cn/web/api/window/setinterval/index.html deleted file mode 100644 index 385a19b81b..0000000000 --- a/files/zh-cn/web/api/window/setinterval/index.html +++ /dev/null @@ -1,635 +0,0 @@ ---- -title: window.setInterval -slug: Web/API/Window/setInterval -tags: - - API - - DOM - - 定时 - - 方法 - - 时间 -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval ---- -<div>{{ ApiRef("HTML DOM") }}</div> - -<p>{{domxref("WindowOrWorkerGlobalScope")}} 的 <strong><code>setInterval()</code> </strong>方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。</p> - -<p><span class="seoSummary">在窗口和工作接口上提供的<strong>setInterval()</strong>方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个时间间隔ID,该ID唯一地标识时间间隔,因此您可以稍后通过调用<strong>clearInterval()</strong>来删除它。这个方法是由<strong>WindowOrWorkerGlobalScope mixin</strong>定义的。</span></p> - -<h2 id="语法">语法</h2> - -<pre class="syntaxbox notranslate"><em>var intervalID</em> = scope.setInterval(<em>func</em>, <em>delay</em>, [<em>arg1</em>, <em>arg2</em>, ...]); -<em>var intervalID</em> = scope.setInterval(<em>code</em>, <em>delay</em>); -</pre> - -<h3 id="参数">参数</h3> - -<dl> - <dt><code>func</code></dt> - <dd>要重复调用的函数。 每经过指定 <code>延迟</code> 毫秒后执行的{{jsxref("函数")}} 。该函数不接受任何参数,也没有返回值。</dd> - <dt><code>code</code></dt> - <dd>这个语法是可选的,你可以传递一个字符串来代替一个函数对象,你传递的字符串会被编译然后每个delay毫秒时间内执行一次。这个语法因为存在安全风险所以不被推荐使用。</dd> - <dt><code>delay</code></dt> - <dd>是每次延迟的毫秒数 (一秒等于1000毫秒),函数的每次调用会在该延迟之后发生。和<a href="/en-US/docs/DOM/window.setTimeout#Minimum_delay_and_timeout_nesting" title="en-US/docs/DOM/window.setTimeout#Minimum delay and timeout nesting">setTimeout</a>一样,实际的延迟时间可能会稍长一点。这个时间计算单位是毫秒(千分之一秒),这个定时器会使指定方法或者代码段执行的时候进行时间延迟。如果这个参数值小于10,则默认使用值为10。请注意,真正延迟时间或许更长; 请参考示例: {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} </dd> - <dt><code>arg1, ..., argN</code> {{optional_inline}}</dt> - <dd>当定时器过期的时候,将被传递给func指定函数的附加参数。</dd> -</dl> - -<h3 id="返回值">返回值</h3> - -<p>此返回值<code>intervalID</code>是一个非零数值,用来标识通过<code>setInterval()</code>创建的计时器,这个值可以用来作为<code>clearInterval()</code>的参数来清除对应的计时器 。</p> - -<p>值得注意的是,<code>setInterval()</code>和<code>setTimeout()</code>共享同一个ID池,并且<code>clearInterval()</code>和<code>clearTimeout()</code>在技术上是可互换使用的。但是,我们必须去匹配<code>clearInterval()</code>和<code>clearTimeout()</code>对应的<code>id,以</code>避免代码杂乱无章,增强代码的可维护性。</p> - -<div class="note"><strong>Note</strong>: The <code>delay</code> argument is converted to a signed 32-bit integer. This effectively limits <code>delay</code> to 2147483647 ms, since it's specified as a signed integer in the IDL.</div> - -<h2 id="示例">示例</h2> - -<h3 id="例1:基本用法">例1:基本用法</h3> - -<p>下面例子是 <code>setInterval()</code>的基本语法</p> - -<pre class="brush:js notranslate">var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2'); - -function myCallback(a, b) -{ - // Your code here - // Parameters are purely optional. - console.log(a); - console.log(b); -} -</pre> - -<h3 id="例2:两种颜色的切换">例2:两种颜色的切换</h3> - -<p>下面的例子里会每隔一秒就调用函数 <code>flashtext()</code> 一次,直至你通过按下 Stop 按钮来清除本次重复操作的唯一辨识符 <code>intervalID</code>。</p> - -<pre class="brush:html notranslate"><!DOCTYPE html> -<html> -<head> - <meta charset="UTF-8" /> - <title>setInterval/clearInterval example</title> - - <script> - var nIntervId; - - function changeColor() { - nIntervId = setInterval(flashText, 1000); - } - - function flashText() { - var oElem = document.getElementById('my_box'); - oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red'; - // oElem.style.color == 'red' ? 'blue' : 'red' is a ternary operator. - } - - function stopTextColor() { - clearInterval(nIntervId); - } - </script> -</head> - -<body onload="changeColor();"> - <div id="my_box"> - <p>Hello World</p> - </div> - - <button onclick="stopTextColor();">Stop</button> -</body> -</html> -</pre> - -<h3 id="例3:打字机效果">例3:打字机效果</h3> - -<p>下面这个例子通过键入、删除和再次键入所有 <a href="/en-US/docs/DOM/NodeList"><code>NodeList</code></a> 中的符合特定的选择器的字符,以达到打字机的效果。</p> - -<div> -<pre class="brush:html notranslate"><!DOCTYPE html> -<html> -<head> -<meta charset="UTF-8" /> -<title>JavaScript Typewriter - MDN Example</title> -<script> -function Typewriter (sSelector, nRate) { - - function clean () { - clearInterval(nIntervId); - bTyping = false; - bStart = true; - oCurrent = null; - aSheets.length = nIdx = 0; - } - - function scroll (oSheet, nPos, bEraseAndStop) { - if (!oSheet.hasOwnProperty("parts") || aMap.length < nPos) { return true; } - - var oRel, bExit = false; - - if (aMap.length === nPos) { aMap.push(0); } - - while (aMap[nPos] < oSheet.parts.length) { - oRel = oSheet.parts[aMap[nPos]]; - - scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true; - - if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) { - bExit = true; - oCurrent = oRel.ref; - sPart = oCurrent.nodeValue; - oCurrent.nodeValue = ""; - } - - oSheet.ref.appendChild(oRel.ref); - if (bExit) { return false; } - } - - aMap.length--; - return true; - } - - function typewrite () { - if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; } - - oCurrent.nodeValue += sPart.charAt(0); - sPart = sPart.slice(1); - } - - function Sheet (oNode) { - this.ref = oNode; - if (!oNode.hasChildNodes()) { return; } - this.parts = Array.prototype.slice.call(oNode.childNodes); - - for (var nChild = 0; nChild < this.parts.length; nChild++) { - oNode.removeChild(this.parts[nChild]); - this.parts[nChild] = new Sheet(this.parts[nChild]); - } - } - - var - nIntervId, oCurrent = null, bTyping = false, bStart = true, - nIdx = 0, sPart = "", aSheets = [], aMap = []; - - this.rate = nRate || 100; - - this.play = function () { - if (bTyping) { return; } - if (bStart) { - var aItems = document.querySelectorAll(sSelector); - - if (aItems.length === 0) { return; } - for (var nItem = 0; nItem < aItems.length; nItem++) { - aSheets.push(new Sheet(aItems[nItem])); - /* Uncomment the following line if you have previously hidden your elements via CSS: */ - // aItems[nItem].style.visibility = "visible"; - } - - bStart = false; - } - - nIntervId = setInterval(typewrite, this.rate); - bTyping = true; - }; - - this.pause = function () { - clearInterval(nIntervId); - bTyping = false; - }; - - this.terminate = function () { - oCurrent.nodeValue += sPart; - sPart = ""; - for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false)); - clean(); - }; -} - -/* usage: */ -var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15); - -/* default frame rate is 100: */ -var oTWExample2 = new Typewriter("#controls"); - -/* you can also change the frame rate value modifying the "rate" property; for example: */ -// oTWExample2.rate = 150; - -onload = function () { - oTWExample1.play(); - oTWExample2.play(); -}; -</script> -<style type="text/css"> -span.intLink, a, a:visited { - cursor: pointer; - color: #000000; - text-decoration: underline; -} - -#info { - width: 180px; - height: 150px; - float: right; - background-color: #eeeeff; - padding: 4px; - overflow: auto; - font-size: 12px; - margin: 4px; - border-radius: 5px; - /* visibility: hidden; */ -} -</style> -</head> - -<body> - -<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p> -<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</span>&nbsp;]</p> -<div id="info"> -Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. -</div> -<h1>JavaScript Typewriter</h1> - -<div id="article"> -<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p> -<form> -<p>Phasellus ac nisl lorem: <input type="text" /><br /> -<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p> -<input type="submit" value="Send" /> -</form> -<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p> -<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p> -</div> -</body> -</html></pre> -</div> - -<p><a href="/files/3997/typewriter.html">查看示例效果</a>,亦可参考:<a href="https://developer.mozilla.org/zh-CN/docs/DOM/window.clearInterval" title="en-US/docs/DOM/window.clearInterval"><code>clearInterval()</code></a>。</p> - -<h2 id="回调参数">回调参数</h2> - -<p>如前所述,Internet Explorer 9及以下版本不支持在<code>setTimeout()</code>或<code>setInterval()</code>中向回调函数传递参数。下面的IE专用代码演示了一种克服这种限制的方法。使用时,只需将以下代码添加到你的脚本顶部即可。</p> - -<pre class="brush:js notranslate">/*\ -|*| -|*| IE-specific polyfill that enables the passage of arbitrary arguments to the -|*| callback functions of javascript timers (HTML5 standard syntax). -|*| -|*| https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval -|*| https://developer.mozilla.org/User:fusionchess -|*| -|*| Syntax: -|*| var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]); -|*| var timeoutID = window.setTimeout(code, delay); -|*| var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]); -|*| var intervalID = window.setInterval(code, delay); -|*| -\*/ - -if (document.all && !window.setTimeout.isPolyfill) { - var __nativeST__ = window.setTimeout; - window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeST__(vCallback instanceof Function ? function () { - vCallback.apply(null, aArgs); - } : vCallback, nDelay); - }; - window.setTimeout.isPolyfill = true; -} - -if (document.all && !window.setInterval.isPolyfill) { - var __nativeSI__ = window.setInterval; - window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeSI__(vCallback instanceof Function ? function () { - vCallback.apply(null, aArgs); - } : vCallback, nDelay); - }; - window.setInterval.isPolyfill = true; -} -</pre> - -<p>另一种方式是使用匿名函数调用你的回调函数,但是这种方式开销较大。例如:</p> - -<pre class="brush:js notranslate">var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);</pre> - -<p>还有一种方式是使用 <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">function's bind</a>. 例如:</p> - -<pre class="brush:js notranslate">var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);</pre> - -<p>{{h3_gecko_minversion("Inactive tabs", "5.0")}}</p> - -<p>Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.</p> - -<h2 id="this_的问题">"<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>" 的问题</h2> - -<p>当你给 <code>setInterval()</code> 传递一个方法或者函数的时候,<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> 值的绑定会存在一些问题。 这个问题在<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method">JavaScript 参考</a> 进行了详细解释。</p> - -<h3 id="解释">解释</h3> - -<p>Code executed by <code>setInterval()</code> runs in a separate execution context than the function from which it was called. As a consequence, the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> keyword for the called function is set to the <code>window</code> (or <code>global</code>) object, it is not the same as the <code>this</code> value for the function that called <code>setTimeout</code>. See the following example (which uses <code>setTimeout()</code> instead of <code>setInterval()</code> – the problem, in fact, is the same for both timers):</p> - -<pre class="brush:js notranslate">myArray = ['zero', 'one', 'two']; - -myArray.myMethod = function (sProperty) { - alert(arguments.length > 0 ? this[sProperty] : this); -}; - -myArray.myMethod(); // prints "zero,one,two" -myArray.myMethod(1); // prints "one" -setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second -setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds -// passing the 'this' object with .call won't work -// because this will change the value of this inside setTimeout itself -// while we want to change the value of this inside myArray.myMethod -// in fact, it will be an error because setTimeout code expects this to be the window object: -setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object" -setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error -</pre> - -<p>As you can see there are no ways to pass the <code>this</code> object to the callback function in the legacy JavaScript.</p> - -<h3 id="一个可能的解决方案">一个可能的解决方案</h3> - -<p>A possible way to solve the "<code>this</code>" problem is to replace the two native <code>setTimeout()</code> or <code>setInterval()</code> global functions with two <em>non-native</em> ones that enable their invocation through the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a> method. The following example shows a possible replacement:</p> - -<pre class="brush:js notranslate">// Enable the passage of the 'this' object through the JavaScript timers - -var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval; - -window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeST__(vCallback instanceof Function ? function () { - vCallback.apply(oThis, aArgs); - } : vCallback, nDelay); -}; - -window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeSI__(vCallback instanceof Function ? function () { - vCallback.apply(oThis, aArgs); - } : vCallback, nDelay); -};</pre> - -<div class="note">These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as <em>non-standard-compliant</em> polyfills also. See the <a href="#Callback_arguments">callback arguments paragraph</a> for a <em>standard-compliant</em> polyfill.</div> - -<p>New feature test:</p> - -<pre class="brush:js notranslate">myArray = ['zero', 'one', 'two']; - -myArray.myMethod = function (sProperty) { - alert(arguments.length > 0 ? this[sProperty] : this); -}; - -setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but... -setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds -setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds -</pre> - -<p>Another, more complex, solution for<strong> </strong>the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> problem<strong> </strong>is <a href="#MiniDaemon_-_A_framework_for_managing_timers">the following framework</a>.</p> - -<div class="note">JavaScript 1.8.5 introduces the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind()</a></code> method, which lets you specify the value that should be used as <code>this</code> for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.</div> - -<h2 id="MiniDaemon:一个用于管理定时器的小框架">MiniDaemon:一个用于管理定时器的小框架</h2> - -<p>In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> object to the callback function (see <a href="#The_.22this.22_problem">The "this" problem</a> for details). The following code is also <a href="https://github.com/madmurphy/minidaemon.js">available on GitHub</a>.</p> - -<div class="note">For a more complex but still modular version of it (<code><em>Daemon</em></code>) see <a href="/en-US/Add-ons/Code_snippets/Timers/Daemons">JavaScript Daemons Management</a>. This more complex version is nothing but a big and scalable collection of methods for the <code><em>Daemon</em></code> constructor. However, the <code><em>Daemon</em></code> constructor itself is nothing but a clone of <code><em>MiniDaemon</em></code> with an added support for <em>init</em> and <em>onstart</em> functions declarable during the instantiation of the <code><em>daemon</em></code>. <strong>So the <code><em>MiniDaemon</em></code> framework remains the recommended way for simple animations</strong>, because <code><em>Daemon</em></code> without its collection of methods is essentially a clone of it.</div> - -<h3 id="minidaemon.js">minidaemon.js</h3> - -<div> -<pre class="brush:js notranslate">/*\ -|*| -|*| :: MiniDaemon :: -|*| -|*| Revision #2 - September 26, 2014 -|*| -|*| https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval -|*| https://developer.mozilla.org/User:fusionchess -|*| https://github.com/madmurphy/minidaemon.js -|*| -|*| This framework is released under the GNU Lesser General Public License, version 3 or later. -|*| http://www.gnu.org/licenses/lgpl-3.0.html -|*| -\*/ - -function MiniDaemon (oOwner, fTask, nRate, nLen) { - if (!(this && this instanceof MiniDaemon)) { return; } - if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); } - if (oOwner) { this.owner = oOwner; } - this.task = fTask; - if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); } - if (nLen > 0) { this.length = Math.floor(nLen); } -} - -MiniDaemon.prototype.owner = null; -MiniDaemon.prototype.task = null; -MiniDaemon.prototype.rate = 100; -MiniDaemon.prototype.length = Infinity; - - /* These properties should be read-only */ - -MiniDaemon.prototype.SESSION = -1; -MiniDaemon.prototype.INDEX = 0; -MiniDaemon.prototype.PAUSED = true; -MiniDaemon.prototype.BACKW = true; - - /* Global methods */ - -MiniDaemon.forceCall = function (oDmn) { - oDmn.INDEX += oDmn.BACKW ? -1 : 1; - if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; } - return true; -}; - - /* Instances methods */ - -MiniDaemon.prototype.isAtEnd = function () { - return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length; -}; - -MiniDaemon.prototype.synchronize = function () { - if (this.PAUSED) { return; } - clearInterval(this.SESSION); - this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this); -}; - -MiniDaemon.prototype.pause = function () { - clearInterval(this.SESSION); - this.PAUSED = true; -}; - -MiniDaemon.prototype.start = function (bReverse) { - var bBackw = Boolean(bReverse); - if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; } - this.BACKW = bBackw; - this.PAUSED = false; - this.synchronize(); -}; -</pre> -</div> - -<div class="note">MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.</div> - -<h3 id="语法_2">语法</h3> - -<p><code>var myDaemon = new MiniDaemon(<em>thisObject</em>, <em>callback</em>[</code><code>, <em>rate</em></code><code>[, <em>length</em>]]);</code></p> - -<h3 id="说明">说明</h3> - -<p>Returns a JavaScript <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>Object</code></a> containing all information needed by an animation (like the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> object, the callback function, the length, the frame-rate).</p> - -<h4 id="参数_2">参数</h4> - -<dl> - <dt><code>thisObject</code></dt> - <dd>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> object on which the <em>callback</em> function is called. It can be an <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>object</code></a> or <code>null</code>.</dd> - <dt><code>callback</code></dt> - <dd>The function that is repeatedly invoked . <strong>It is called with three arguments</strong>: <em>index</em> (the iterative index of each invocation), <em>length</em> (the number of total invocations assigned to the <em>daemon</em> - finite or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) and <em>backwards</em> (a boolean expressing whether the <em>index</em> is increasing or decreasing). It is something like <em>callback</em>.call(<em>thisObject</em>, <em>index</em>, <em>length</em>, <em>backwards</em>). <strong>If the callback function returns a <code>false</code> value the <em>daemon</em> is paused</strong>.</dd> - <dt><code>rate (optional)</code></dt> - <dd>The time lapse (in number of milliseconds) between each invocation. The default value is 100.</dd> - <dt><code>length (optional)</code></dt> - <dd>The total number of invocations. It can be a positive integer or <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>. The default value is <code>Infinity</code>.</dd> -</dl> - -<h4 id="MiniDaemon_实例(instance)的属性"><code>MiniDaemon</code> 实例(instance)的属性</h4> - -<dl> - <dt><code>myDaemon.owner</code></dt> - <dd>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a> object on which is executed the daemon (read/write). It can be an <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><code>object</code></a> or <code>null</code>.</dd> - <dt><code>myDaemon.task</code></dt> - <dd>The function that is repeatedly invoked (read/write). It is called with three arguments: <em>index</em> (the iterative index of each invocation), <em>length</em> (the number of total invocations assigned to the daemon - finite or <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>) and backwards (a boolean expressing whether the <em>index</em> is decreasing or not) – see above. If the <code>myDaemon.task</code> function returns a <code>false</code> value the <em>daemon</em> is paused.</dd> - <dt><code>myDaemon.rate</code></dt> - <dd>The time lapse (in number of milliseconds) between each invocation (read/write).</dd> - <dt><code>myDaemon.length</code></dt> - <dd>The total number of invocations. It can be a positive integer or <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a> (read/write).</dd> -</dl> - -<h4 id="MiniDaemon_实例的方法"><code>MiniDaemon</code> 实例的方法</h4> - -<dl> - <dt><code>myDaemon.isAtEnd()</code></dt> - <dd>Returns a boolean expressing whether the <em>daemon</em> is at the start/end position or not.</dd> - <dt><code>myDaemon.synchronize()</code></dt> - <dd>Synchronize the timer of a started daemon with the time of its invocation.</dd> - <dt><code>myDaemon.pause()</code></dt> - <dd>Pauses the daemon.</dd> - <dt><code>myDaemon.start([<em>reverse</em>])</code></dt> - <dd>Starts the daemon forward (<em>index</em> of each invocation increasing) or backwards (<em>index</em> decreasing).</dd> -</dl> - -<h4 id="MiniDaemon_全局对象的方法"><code>MiniDaemon</code> 全局对象的方法</h4> - -<dl> - <dt><code>MiniDaemon.forceCall(<em>minidaemon</em>)</code></dt> - <dd>Forces a single callback to the <code><em>minidaemon</em>.task</code> function regardless of the fact that the end has been reached or not. In any case the internal <code>INDEX</code> property is increased/decreased (depending on the actual direction of the process).</dd> -</dl> - -<h3 id="使用示例">使用示例</h3> - -<p>HTML:</p> - -<pre class="brush:html notranslate"><!DOCTYPE html> -<html> -<head> - <meta charset="UTF-8" /> - <title>MiniDaemin Example - MDN</title> - <script type="text/javascript" src="minidaemon.js"></script> - <style type="text/css"> - #sample_div { - visibility: hidden; - } - </style> -</head> - -<body> - <p> - <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" /> - <input type="button" onclick="fadeInOut.start(true);" value="fade out"> - <input type="button" onclick="fadeInOut.pause();" value="pause" /> - </p> - - <div id="sample_div">Some text here</div> - - <script type="text/javascript"> - function opacity (nIndex, nLength, bBackwards) { - this.style.opacity = nIndex / nLength; - if (bBackwards ? nIndex === 0 : nIndex === 1) { - this.style.visibility = bBackwards ? 'hidden' : 'visible'; - } - } - - var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8); - </script> -</body> -</html></pre> - -<p><a href="/files/3995/minidaemon_example.html" title="MiniDaemon Example">View this example in action</a></p> - -<h2 id="备注">备注</h2> - -<p>The <code>setInterval()</code> function is commonly used to set a delay for functions that are executed again and again, such as animations.</p> - -<p>You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.</p> - -<p>If you wish to have your function called <em>once</em> after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.</p> - -<h3 id="Ensure_that_execution_duration_is_shorter_than_interval_frequency">Ensure that execution duration is shorter than interval frequency</h3> - -<p>If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using <code>setInterval</code> to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.</p> - -<p>In these cases, a recursive <code>setTimeout()</code> pattern is preferred:</p> - -<pre class="brush:js notranslate">(function loop(){ - setTimeout(function() { - // Your logic here - - loop(); - }, delay); -})(); -</pre> - -<p>In the above snippet, a named function <code>loop()</code> is declared and is immediately executed. <code>loop()</code> is recursively called inside <code>setTimeout()</code> after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.</p> - -<h3 id="Throttling_of_intervals">Throttling of intervals</h3> - -<p><code>setInterval()</code> is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see <a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified">Reasons for delays longer than specified</a>.</p> - -<h2 id="规范">规范</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th>Specification</th> - <th>Status</th> - <th>Comment</th> - </tr> - <tr> - <td>{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}</td> - <td>{{Spec2("HTML WHATWG")}}</td> - <td>Method moved to the <code>WindowOrWorkerGlobalScope</code> mixin in the latest spec.</td> - </tr> - <tr> - <td>{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}</td> - <td>{{Spec2("HTML WHATWG")}}</td> - <td>Initial definition (DOM Level 0)</td> - </tr> - </tbody> -</table> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<div> - - -<p>{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}</p> -</div> - -<h2 id="参见">参见</h2> - -<ul> - <li><a href="/en-US/Add-ons/Code_snippets/Timers">JavaScript 定时器</a></li> - <li>{{domxref("WindowOrWorkerGlobalScope.setTimeout")}}</li> - <li>{{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}</li> - <li>{{domxref("WindowOrWorkerGlobalScope.clearInterval")}}</li> - <li>{{domxref("window.requestAnimationFrame")}}</li> - <li><a href="/en-US/Add-ons/Code_snippets/Timers/Daemons"><em>Daemons</em> management</a></li> -</ul> diff --git a/files/zh-cn/web/api/window/settimeout/index.html b/files/zh-cn/web/api/window/settimeout/index.html deleted file mode 100644 index f9813851f7..0000000000 --- a/files/zh-cn/web/api/window/settimeout/index.html +++ /dev/null @@ -1,476 +0,0 @@ ---- -title: window.setTimeout -slug: Web/API/Window/setTimeout -tags: - - Timers - - WindowOrWorkerGlobalScope - - WindowTimers - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout ---- -<p>{{APIRef("HTML DOM")}}</p> - -<p> {{domxref("WindowOrWorkerGlobalScope")}} 混合的 <strong><code>setTimeout()</code></strong>方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。</p> - -<h2 id="Syntax" name="Syntax">语法</h2> - -<pre class="syntaxbox notranslate"><code>var<em> </em>timeoutID = <em>scope</em>.setTimeout(<em>function</em>[<em>,</em> <em>delay, arg1, arg2</em>, ...]); -var timeoutID = <em>scope</em>.setTimeout(function[, <em>delay</em>]); -var<em> </em>timeoutID = <em>scope</em>.setTimeout(<em>code</em>[, <em>delay</em>]);</code></pre> - -<h3 id="参数">参数</h3> - -<dl> - <dt><code>function</code></dt> - <dd>{{jsxref("function")}} 是你想要在到期时间(<code>delay</code>毫秒)之后执行的<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="en-US/docs/Core_JavaScript_1.5_Reference/Global_Objects/Function">函数</a>。</dd> - <dt><code>code</code></dt> - <dd>这是一个可选语法,你可以使用字符串而不是{{jsxref("function")}} ,在<code>delay</code>毫秒之后编译和执行字符串 (使用该语法是<strong>不推荐的,</strong> 原因和使用 {{jsxref("Global_Objects/eval", "eval()")}}一样,有安全风险)。</dd> - <dt><code>delay</code> {{optional_inline}}</dt> - <dd>延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,原因请查看{{anch("实际延时比设定值更久的原因:最小延迟时间")}}。</dd> - <dt><code>arg1, ..., argN</code> {{optional_inline}}</dt> - <dd>附加参数,一旦定时器到期,它们会作为参数传递给{{jsxref("function")}} </dd> -</dl> - -<div class="note"> -<p><strong>备注</strong>:需要注意的是,IE9 及更早的 IE 浏览器不支持向回调函数传递额外参数(第一种语法)。如果你想要在IE中达到同样的功能,你必须使用一种兼容代码 (查看 {{anch("兼容旧环境(polyfill)")}} 一段).</p> -</div> - -<h3 id="Examples" name="Examples">返回值</h3> - -<p>返回值<code>timeoutID</code>是一个正整数,表示定时器的编号。这个值可以传递给{{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}来取消该定时器。</p> - -<p>需要注意的是<code>setTimeout()</code>和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}共用一个编号池,技术上,<code>clearTimeout()</code>和 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 可以互换。但是,为了避免混淆,不要混用取消定时函数。</p> - -<p>在同一个对象上(一个window或者worker),<code>setTimeout()</code>或者<code>setInterval()</code>在后续的调用不会重用同一个定时器编号。但是不同的对象使用独立的编号池。</p> - -<h2 id="例子">例子</h2> - -<p>下文的例子在网页中设置了两个简单的按钮,以触发 <code>setTimeout()</code> 和 <code>clearTimeout()</code> 方法:按下第一个按钮会设置一个定时器,定时器在 2s 后显示一个警告对话框,并将此次 setTimeout 的定时器 ID 保存起来,按下第二个按钮可以取消定时器。</p> - -<h3 id="HTML" style="line-height: 24px; font-size: 1.71428571428571rem;">HTML</h3> - -<pre class="brush: html notranslate"><p>Live Example</p> -<button onclick="delayedAlert();">Show an alert box after two seconds</button> -<p></p> -<button onclick="clearAlert();">Cancel alert before it happens</button> -</pre> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"></div> - -<h3 id="JavaScript" style="line-height: 24px; font-size: 1.71428571428571rem;">JavaScript</h3> - -<pre class="brush: js notranslate">var timeoutID; - -function delayedAlert() { - timeoutID = window.setTimeout(slowAlert, 2000); -} - -function slowAlert() { - alert('That was really slow!'); -} - -function clearAlert() { - window.clearTimeout(timeoutID); -} -</pre> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 76px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 95px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 152px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 171px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 190px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 209px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 228px; background: 0px 0px;"></div> - -<h3 id="结果展示">结果展示</h3> - -<p>{{EmbedLiveSample('例子')}}</p> - -<p>也可参考 <a href="/en-US/docs/DOM/window.clearTimeout#Example" title="en-US/docs/DOM/window.clearTimeout#Example"><code>clearTimeout()</code> </a>示例.</p> - -<h2 id="兼容旧环境(polyfill)">兼容旧环境(polyfill)</h2> - -<p>如果你需要向你的回调函数内传递一个或多个参数, 而且还需要兼容那些不支持传递额外参数(不管使用<code>setTimeout()</code> 或者 <code>setInterval()</code>)的浏览器时(比如,IE9及更早的版本), 你可以引入下面的兼容代码来支持向定时器函数传参。将以下代码添加到你代码的最上面:</p> - -<pre class="brush: js notranslate">/*\ -|*| -|*| Polyfill which enables the passage of arbitrary arguments to the -|*| callback functions of JavaScript timers (HTML5 standard syntax). -|*| -|*| https://developer.mozilla.org/en-US/docs/DOM/window.setInterval -|*| -|*| Syntax: -|*| var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]); -|*| var timeoutID = window.setTimeout(code, delay); -|*| var intervalID = window.setInterval(func, delay[, param1, param2, ...]); -|*| var intervalID = window.setInterval(code, delay); -|*| -\*/ - -(function() { - setTimeout(function(arg1) { - if (arg1 === 'test') { - // feature test is passed, no need for polyfill - return; - } - var __nativeST__ = window.setTimeout; - window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) { - var aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeST__(vCallback instanceof Function ? function() { - vCallback.apply(null, aArgs); - } : vCallback, nDelay); - }; - }, 0, 'test'); - - var interval = setInterval(function(arg1) { - clearInterval(interval); - if (arg1 === 'test') { - // feature test is passed, no need for polyfill - return; - } - var __nativeSI__ = window.setInterval; - window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) { - var aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeSI__(vCallback instanceof Function ? function() { - vCallback.apply(null, aArgs); - } : vCallback, nDelay); - }; - }, 0, 'test'); -}())</pre> - -<h3 id="针对IE的解决方法">针对IE的解决方法</h3> - -<p>如果你需要单独的针对IE9及之前浏览器的 hack 写法,你可以使用 JavaScript 条件注释:</p> - -<pre class="brush: js notranslate">/*@cc_on - // conditional IE < 9 only fix - @if (@_jscript_version <= 9) - (function(f){ - window.setTimeout = f(window.setTimeout); - window.setInterval = f(window.setInterval); - })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}}); - @end -@*/</pre> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 76px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 95px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 152px; background: 0px 0px;"></div> - -<p>或者使用更加清晰的 IE HTML 条件注释:</p> - -<pre class="brush: html notranslate"><!--[if lte IE 9]><script> -(function(f){ -window.setTimeout=f(window.setTimeout); -window.setInterval=f(window.setInterval); -})(function(f){return function(c,t){ -var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)} -}); -</script><![endif]--> - - -</pre> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"></div> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"></div> - -<h3 id="变通方法">变通方法</h3> - -<p>另一种方法是使用匿名函数包裹你的回调函数,这种方式要消耗更多资源:</p> - -<pre class="brush: js notranslate">var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000); -</pre> - -<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> - -<p>上面那个例子也可以用<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>:</p> - -<pre class="brush: js notranslate">var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000); -</pre> - -<p>此外,也可使用 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">function's bind</a>:</p> - -<pre class="brush: js notranslate">setTimeout(function(arg1){}.bind(undefined, 10), 1000); -</pre> - -<h2 id="关于this的问题">关于"<code>this</code>"的问题</h2> - -<p>当你向 <code>setTimeout()</code> (或者其他函数)传递一个函数时,该函数中的<code>this</code>指向跟你的期望可能不同,这个问题在 <a href="/en-US/docs/JavaScript/Reference/Operators/this#Method_binding" title="en-US/docs/Core_JavaScript_1.5_Reference/Operators/Special_Operators/this_Operator#Method_binding">JavaScript reference</a> 中进行了详细解释.</p> - -<h3 id="解释">解释</h3> - -<p>由<code>setTimeout()</code>调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 <code>this</code> 关键字在非严格模式会指向 <code>window</code> (或全局)对象,严格模式下为 undefined,这和所期望的<code>this</code>的值是不一样的。</p> - -<div class="note"> -<p>备注:即使是在严格模式下,<code>setTimeout()</code>的回调函数里面的<code>this</code>仍然默认指向<code>window</code>对象, 并不是<code>undefined</code>。</p> -</div> - -<p>查看下面的例子:</p> - -<pre class="brush: js notranslate">let myArray = ["zero", "one", "two"]; -myArray.myMethod = function (sProperty) { - alert(arguments.length > 0 ? this[sProperty] : this); -}; - -myArray.myMethod(); // prints "zero,one,two" -myArray.myMethod(1); // prints "one"</pre> - -<p>上面这段代码正常工作,用<code>myArray</code>调用,在函数内,<code>this[sProperty]</code>等于 <code>myArray[sProperty]</code>。然后,下面这个例子:</p> - -<pre class="brush: js notranslate">setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second -setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds</pre> - -<p><code>myArray.myMethod</code>函数传递给 <code>setTimeout</code>,到了定时时间,<code>this</code>没有指向,默认指向<code>window</code>对象。并且没有方法把 <code>thisArg</code> 传递给<code>setTimeout</code>,正如Array方法的<code>forEach</code>,<code>reduce</code>等。下面的例子表示使用<code>call</code>方法设置<code>this</code>也没用。</p> - -<pre class="brush: js notranslate">setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object" -setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error</pre> - -<h3 id="可能的解决方案">可能的解决方案</h3> - -<p>一个通用的方法是用包装函数来设置<code>this</code>:</p> - -<pre class="brush: js notranslate">setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds -setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds</pre> - -<p>箭头函数也可以:</p> - -<pre class="brush: js notranslate">setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds -setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds</pre> - -<p>另一个解决<code>this</code>问题的方法是使用两个非原生的 <code>setTimeout()</code> 和 <code>setInterval()</code> 全局函数代替原生的。该非原生的函数通过使用<a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a> 方法激活了正确的作用域。下面的代码显示了应该如何替换:</p> - -<pre class="brush: js notranslate">// Enable the passage of the 'this' object through the JavaScript timers - -var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval; - -window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeST__(vCallback instanceof Function ? function () { - vCallback.apply(oThis, aArgs); - } : vCallback, nDelay); -}; - -window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) { - var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2); - return __nativeSI__(vCallback instanceof Function ? function () { - vCallback.apply(oThis, aArgs); - } : vCallback, nDelay); -};</pre> - -<div class="note"><strong>备注:</strong> 这两个替换也让 IE支持了符合 HTML5 标准的定时器函数。所以也能作为一个 polyfills。查看 <a href="#Callback_arguments">Callback arguments</a> 一段.</div> - -<p>新特性检测:</p> - -<pre class="brush: js notranslate">let myArray = ["zero", "one", "two"]; -myArray.myMethod = function (sProperty) { - alert(arguments.length > 0 ? this[sProperty] : this); -}; - -setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but... -setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds -setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds -</pre> - -<p>针对这个问题并没有原生的解决方案。</p> - -<div class="note"><strong>注:</strong>JavaScript 1.8.5 引入了 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/docs/JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind()</a></code> 方法,该方法允许显式地指定函数调用时 this 所指向的值 。该方法可以帮助你解决 this 指向不确定的问题。</div> - -<p>使用<code>bind()</code>的例子:</p> - -<pre class="brush: js notranslate">let myArray = ['zero', 'one', 'two']; -myBoundMethod = (function (sProperty) { - console.log(arguments.length > 0 ? this[sProperty] : this); -}).bind(myArray); - -myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function -myBoundMethod(1); // prints "one" -setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding -setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds -</pre> - -<h2 id="备注">备注</h2> - -<p>你可以使用 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()","clearTimeout()")}}来取消定时器。</p> - -<p>如果你希望你的代码被重复的调用 (比如每 N 毫秒一次),考虑使用{{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}。</p> - -<h3 id="传递字符串字面量">传递字符串字面量</h3> - -<p>向<code>setTimeout()</code>传递一个字符串而不是函数会遭受到与使用<code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21" title="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/eval">eval</a></code>一样的风险.</p> - -<pre class="brush: js notranslate">// 推荐 -window.setTimeout(function() { - alert("Hello World!"); -}, 500); - -// 不推荐 -window.setTimeout("alert(\"Hello World!\");", 500); - -</pre> - -<p>字符串会在全局作用域内被解释执行,所以当<code>setTimeout()</code>函数执行完毕后,字符串中的变量不可用.</p> - -<h3 id="实际延时比设定值更久的原因:最小延迟时间">实际延时比设定值更久的原因:最小延迟时间</h3> - -<p>有很多因素会导致setTimeout的回调函数执行比设定的预期值更久,本节将讨论最常见的原因。</p> - -<h4 id="最小延时_>4ms">最小延时 >=4ms</h4> - -<p>在浏览器中,<code>setTimeout()/</code>{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。例如:</p> - -<pre class="brush: js notranslate" id="ct-0"><code>function cb() { f(); setTimeout(cb, 0); } -setTimeout(cb, 0);</code></pre> - -<pre class="brush: js notranslate"><code>setInterval(f, 0);</code></pre> - -<p>在Chrome 和 Firefox中, 定时器的第5次调用被阻塞了;在Safari是在第6次;Edge是在第3次。Gecko 从这个版本 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/56">version 56</a>开始对 <code>setInterval()</code> 开始采用这样的机制(<code>setTimeout()</code>已经实现,具体请参考以下内容)。</p> - -<p>一直以来,不同浏览器中出现这种最小延迟的情况有所不同(例如Firefox) - 从其他地方调用了setInterval( ),或者在嵌套函数调用setTimeout( ) 时(嵌套级别达到特定深度时),都会出现超时延迟。</p> - -<p>如果想在浏览器中实现0ms延时的定时器,你可以参考<a href="http://dbaron.org/log/20100309-faster-timeouts">这里</a>所说的{domxref("window.postMessage()")}}</p> - -<div class="note"> -<p><strong>Note</strong>: 最小延时, <code>DOM_MIN_TIMEOUT_VALUE</code>, 是4ms (但在Firefox中通常是是存储在 <code>dom.min_timeout_value </code>这个变量中), <code>DOM_CLAMP_TIMEOUT_NESTING_LEVEL</code> 的第5层.</p> -</div> - -<div class="note"> -<p><strong>Note</strong>: 4 ms 是在 <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers">HTML5 spec </a> 中精确的,并且在2010年及以后的跨浏览器中保持了一致,这个数值比 {{geckoRelease("5.0")}}规定的嵌套函数的最小延时10ms更为精确。</p> -</div> - -<h4 id="未被激活的tabs的定时最小延迟>1000ms">未被激活的tabs的定时最小延迟>=1000ms</h4> - -<p>为了优化后台tab的加载损耗(以及降低耗电量),在未被激活的tab中定时器的最小延时限制为1S(1000ms)。</p> - -<p>Firefox 从version 5 (see {{bug(633421)}}开始采取这种机制,1000ms的间隔值可以通过 <code>dom.min_background_timeout_value</code> 改变。Chrome 从 version 11 (<a href="http://crbug.com/66078">crbug.com/66078</a>)开始采用。</p> - -<p>Android 版的Firefox对未被激活的后台tabs的使用了15min的最小延迟间隔时间 ,并且这些tabs也能完全不被加载。</p> - -<div class="note"> -<p>当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。</p> -</div> - -<h4 id="追踪型脚本的最小延时限制">追踪型脚本的最小延时限制</h4> - -<p>从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 <a href="https://wiki.mozilla.org/Security/Tracking_protection#Lists">TP lists</a> 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。</p> - -<p>控制这些行为的属性包含以下这些:</p> - -<ul> - <li><code>dom.min_tracking_timeout_value</code>: 4</li> - <li><code>dom.min_tracking_background_timeout_value</code>: 10000</li> - <li><code>dom.timeout.tracking_throttling_delay</code>: 30000</li> -</ul> - -<h4 id="超时延迟">超时延迟</h4> - -<p>除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 <code>setTimeout()</code>的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:</p> - -<pre class="notranslate"><code>function foo() { - console.log('foo has been called'); -} -setTimeout(foo, 0); -console.log('After setTimeout');</code></pre> - -<p>会在控制台输出:</p> - -<pre class="notranslate"><code>After setTimeout -foo has been called</code></pre> - -<p>出现这个结果的原因是,尽管<code>setTimeout</code> 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。</p> - -<h3 id="WebExtension_Background_pages和定时器">WebExtension Background pages和定时器</h3> - -<p>在 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions">WebExtension</a> 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在<a href="https://developer.chrome.com/extensions/background_migration">合并到事件驱动后台脚本</a>。</p> - -<p>在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:</p> - -<p>1.兼容Chorme。</p> - -<p>2.未来行为的改变会引起问题。</p> - -<h3 id="最大延时值">最大延时值</h3> - -<p>包括 IE, Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。</p> - -<h2 id="规范">规范</h2> - -<table class="standard-table"> - <thead> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - </thead> - <tbody> - <tr> - <td>{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}</td> - <td>{{Spec2("HTML WHATWG")}}</td> - <td>Method moved to the <code>WindowOrWorkerGlobalScope</code> mixin in the latest spec.</td> - </tr> - <tr> - <td>{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}</td> - <td>{{Spec2("HTML WHATWG")}}</td> - <td>Initial definition (DOM Level 0)</td> - </tr> - </tbody> -</table> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<div id="compat-desktop"> -<div class="hidden"> -<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> -</div> - -<p>{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}</p> -</div> - -<h2 id="See_also" name="See_also" style="margin-bottom: 20px; line-height: 30px; font-size: 2.14285714285714rem;">相关链接:</h2> - -<ul> - <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Timers" title="/en-US/docs/JavaScript/Timers">JavaScript timers</a></li> - <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm">Timer.jsm</a></li> - <li>{{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}</li> - <li>{{domxref("WindowTimers.setInterval")}}</li> - <li>{{domxref("window.requestAnimationFrame")}}</li> - <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Timers/Daemons" title="/en-US/docs/JavaScript/Timers/Daemons"><em>Daemons</em> management</a></li> -</ul> diff --git a/files/zh-cn/web/api/window/unhandledrejection_event/index.html b/files/zh-cn/web/api/window/unhandledrejection_event/index.html new file mode 100644 index 0000000000..9c3286aa44 --- /dev/null +++ b/files/zh-cn/web/api/window/unhandledrejection_event/index.html @@ -0,0 +1,118 @@ +--- +title: unhandledrejection +slug: Web/Events/unhandledrejection +tags: + - API + - JavaScript + - Promise + - unhandledrejection + - 事件 + - 参考 +translation_of: Web/API/Window/unhandledrejection_event +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p><span class="seoSummary">当{{jsxref("Promise")}} 被 reject 且没有 reject 处理器的时候,会触发 <strong><code>unhandledrejection</code></strong> 事件;这可能发生在 {{domxref("window")}} 下,但也可能发生在 {{domxref("Worker")}} 中。</span> 这对于调试回退错误处理非常有用。</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">是否冒泡</th> + <td>No</td> + </tr> + <tr> + <th scope="row">是否可取消</th> + <td>Yes</td> + </tr> + <tr> + <th scope="row">接口</th> + <td>{{domxref("PromiseRejectionEvent")}}</td> + </tr> + <tr> + <th scope="row">事件处理器属性</th> + <td>{{domxref("WindowEventHandlers.onunhandledrejection", "onunhandledrejection")}}</td> + </tr> + </tbody> +</table> + +<h2 id="使用备注">使用备注</h2> + +<p><code>unhandledrejection</code> 继承自 {{domxref("PromiseRejectionEvent")}},而 {{domxref("PromiseRejectionEvent")}} 又继承自 {{domxref("Event")}}。因此<code>unhandledrejection</code> 含有 <code>PromiseRejectionEvent</code> 和 <code>Event</code> 的属性和方法。</p> + +<h2 id="例子">例子</h2> + +<p>Here we have a few examples showing ways you can make use of the <code>unhandledrejection</code> event. The event includes two useful pieces of information:</p> + +<p>我们将通过几个例子来展示 <code>unhandledrejection</code> 事件的使用方式。该事件主要包含两部分有用的信息:</p> + +<dl> + <dt><code>promise</code></dt> + <dd>The actual {{jsxref("Promise")}} which was rejected with no handler available to deal with the rejection.</dd> + <dd>特定的 {{jsxref("Promise")}} 被 reject 而没有被相应的异常处理方法所处理时</dd> + <dt><code>reason</code></dt> + <dd>The reason that would have been passed into the rejection handler if one had existed. See {{jsxref("Promise.catch", "catch()")}} for details.</dd> + <dd>将会传入异常处理方法中的错误原因(如果存在),查看 {{jsxref("Promise.catch", "catch()")}} 相关以获取更多细节。</dd> +</dl> + +<h3 id="基本的异常上报">基本的异常上报</h3> + +<p>此示例只是将有关未处理的 Promise rejection 信息打印到控制台。</p> + +<pre class="brush:js; notranslate">window.addEventListener("unhandledrejection", event => { + console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); +}); +</pre> + +<p>您还可以使用 {{domxref("WindowEventHandlers.onunhandledrejection", "onunhandledrejection")}} 事件处理程序属性来设置事件侦听器:</p> + +<pre class="brush: js notranslate">window.onunhandledrejection = event => { + console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); +}; +</pre> + +<h3 id="防止默认处理">防止默认处理</h3> + +<p>许多环境(例如 {{Glossary("Node.js")}} ) 默认情况下会向控制台打印未处理的 Promise rejections。您可以通过添加一个处理程序来防止 <code>unhandledrejection</code> 这种情况的发生,该处理程序除了您希望执行的任何其他任务之外,还可以调用 {{domxref("Event.preventDefault()", "preventDefault()")}} 来取消该事件,从而防止该事件冒泡并由运行时的日志代码处理。这种方法之所以有效,是因为 <code>unhandledrejection</code> 是可以取消的。</p> + +<pre class="brush:js; notranslate">window.addEventListener('unhandledrejection', function (event) { + // ...您的代码可以处理未处理的拒绝... + + // 防止默认处理(例如将错误输出到控制台) + + event.preventDefault(); +}); +</pre> + +<h2 id="说明">说明</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webappapis.html#unhandled-promise-rejections', 'unhandledrejection')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div class="hidden">此页面上的兼容性表是根据结构化数据生成的。 如果您想提供数据,请查看https://github.com/mdn/browser-compat-data 并向我们发送请求请求。</div> + +<p>{{Compat("api.Window.unhandledrejection_event")}}</p> + +<h2 id="参考">参考</h2> + +<ul> + <li>{{SectionOnPage("/en-US/docs/Web/JavaScript/Guide/Using_promises", "Promise rejection events")}}</li> + <li>{{domxref("WindowEventHandlers.onunhandledrejection", "onunhandledrejection")}} event handler property<sup><a href="#seealso-footnote-1">1</a></sup></li> + <li>{{Event("rejectionhandled")}}</li> + <li>{{domxref("Promise")}}</li> +</ul> + +<p><a id="seealso-footnote-1" name="seealso-footnote-1">[1]</a> The corresponding event handler property is defined on the {{domxref("WindowEventHandlers")}} mixin, which is available on both the {{domxref("Window")}} interface and all types of {{domxref("Worker")}} interfaces.</p> diff --git a/files/zh-cn/web/api/window/unload_event/index.html b/files/zh-cn/web/api/window/unload_event/index.html new file mode 100644 index 0000000000..2510b1f651 --- /dev/null +++ b/files/zh-cn/web/api/window/unload_event/index.html @@ -0,0 +1,125 @@ +--- +title: unload +slug: Web/Events/unload +tags: + - Window + - events + - unload +translation_of: Web/API/Window/unload_event +--- +<p>{{APIRef}}</p> + +<p>当文档或一个子资源正在被卸载时, 触发 <strong>unload</strong>事件。</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">可冒泡(Bubbles)</th> + <td>No</td> + </tr> + <tr> + <th scope="row">可取消(Cancelable)</th> + <td>No</td> + </tr> + <tr> + <th scope="row">接口(Interface)</th> + <td>{{domxref("Event")}}</td> + </tr> + <tr> + <th scope="row">事件处理程序属性(Event handler property)</th> + <td>{{domxref("WindowEventHandlers/onunload", "onunload")}}</td> + </tr> + </tbody> +</table> + +<p>它在下面两个事件后被触发:</p> + +<ol> + <li><a href="/en-US/docs/Mozilla_event_reference/beforeunload" title="/en-US/docs/Mozilla_event_reference/beforeunload">beforeunload</a> (可取消默认行为的事件)</li> + <li><a href="/en-US/docs/Mozilla_event_reference/pagehide" title="/en-US/docs/Mozilla_event_reference/pagehide">pagehide</a></li> +</ol> + +<p>文档处于以下状态:</p> + +<ul> + <li>所有资源仍存在 (图片, iframe 等.)</li> + <li>对于终端用户所有资源均不可见</li> + <li>界面交互无效 (<code>window.open</code>, <code>alert</code>, <code>confirm</code> 等.)</li> + <li>错误不会停止卸载文档的过程</li> +</ul> + +<p>请注意<code>unload</code>事件也遵循文档树:父iframe会在子iframe卸载前卸载(参考下面的例子).</p> + +<h2 id="示例">示例</h2> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> + <head> + <title>Parent Frame</title> + <script> + window.addEventListener('beforeunload', function(event) { + console.log('I am the 1st one.'); + }); + window.addEventListener('unload', function(event) { + console.log('I am the 3rd one.'); + }); + </script> + </head> + <body> + <iframe src="child-frame.html"></iframe> + </body> +</html></pre> + +<p>下面是 <code>child-frame.html的内容</code>:</p> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> + <head> + <title>Child Frame</title> + <script> + window.addEventListener('beforeunload', function(event) { + console.log('I am the 2nd one.'); + }); + window.addEventListener('unload', function(event) { + console.log('I am the 4th and last one…'); + }); + </script> + </head> + <body> + ☻ + </body> +</html></pre> + +<p>当父iframe被卸载,事件将按<code>console.log()</code> 消息描述的顺序触发。</p> + +<h2 id="规范">规范</h2> + +<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-unload', 'unload')}}</td> + <td>{{Spec2('UI Events')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Window.unload_event")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>相关事件: {{domxref("Window/DOMContentLoaded_event", "DOMContentLoaded")}}, {{domxref("Document/readystatechange_event", "readystatechange")}}, {{domxref("Window/load_event", "load")}}</li> + <li><a href="https://html.spec.whatwg.org/multipage/browsers.html#unloading-documents">Unloading Documents — unload a document</a></li> +</ul> diff --git a/files/zh-cn/web/api/window/url/index.html b/files/zh-cn/web/api/window/url/index.html deleted file mode 100644 index 3ca38bbd39..0000000000 --- a/files/zh-cn/web/api/window/url/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Window.URL -slug: Web/API/Window/URL -tags: - - Window.URL -translation_of: Web/API/URL -translation_of_original: Web/API/Window/URL ---- -<p>{{ApiRef("Window")}}{{SeeCompatTable}}</p> - -<p><strong>Window.URL</strong> 属性返回一个对象,它提供了用于创建和管理对象URLs的静态方法。它也可以作为一个构造函数被调用来构造 {{domxref("URL")}} 对象。</p> - -<div class="note"> -<p>Note: 此功能在Web Workers中可用。</p> -</div> - -<h2 id="语法">语法</h2> - -<p>调用一个静态方法:</p> - -<pre class="syntaxbox"><code><var>img</var>.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(<var>blob</var>);</code></pre> - -<p>构造一个新对象:</p> - -<pre class="syntaxbox"><code>var <var>url</var> = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");</code></pre> - -<h2 id="规范">规范</h2> - -<table class="standard-table"> - <tbody> - <tr> - <th scope="col">Specification</th> - <th scope="col">Status</th> - <th scope="col">Comment</th> - </tr> - <tr> - <td>{{SpecName('URL', '#dom-url', 'URL')}}</td> - <td>{{Spec2('URL')}}</td> - <td>Initial definition</td> - </tr> - </tbody> -</table> - -<h2 id="浏览器兼容性">浏览器兼容性</h2> - -<p>{{CompatibilityTable}}</p> - -<div id="compat-desktop"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Chrome</th> - <th>Firefox (Gecko)</th> - <th>Internet Explorer</th> - <th>Opera</th> - <th>Safari</th> - </tr> - <tr> - <td>Basic support</td> - <td>8.0<sup>[2]</sup></td> - <td>{{CompatGeckoDesktop("2.0")}}<sup>[1]</sup><br> - {{CompatGeckoDesktop("19.0")}}</td> - <td>10.0</td> - <td>15.0<sup>[2]</sup></td> - <td>6.0<sup>[2]</sup><br> - 7.0</td> - </tr> - </tbody> -</table> -</div> - -<div id="compat-mobile"> -<table class="compat-table"> - <tbody> - <tr> - <th>Feature</th> - <th>Android</th> - <th>Firefox Mobile (Gecko)</th> - <th>IE Mobile</th> - <th>Opera Mobile</th> - <th>Safari Mobile</th> - </tr> - <tr> - <td>Basic support</td> - <td>{{CompatVersionUnknown}}<sup>[2]</sup></td> - <td>{{CompatGeckoMobile("14.0")}}<sup>[1]</sup><br> - {{CompatGeckoMobile("19.0")}}</td> - <td>{{CompatVersionUnknown}}</td> - <td>15.0<sup>[2]</sup></td> - <td>6.0<sup>[2]</sup></td> - </tr> - </tbody> -</table> -</div> - -<p>[1] 从 Gecko 2 (Firefox 4) 到 包括Gecko 18, Gecko 返回一个不标准的nsIDOMMozURLProperty内部类型. 在实践中, 这是没有意义的.</p> - -<p>[2] 在非标准名称webkitURL下实现。</p> - -<h2 id="也可以看看">也可以看看</h2> - -<ul> - <li>{{domxref("URL")}} API.</li> -</ul> |