From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/window/alert/index.html | 61 ++ .../web/api/window/applicationcache/index.html | 38 ++ files/zh-cn/web/api/window/back/index.html | 26 + files/zh-cn/web/api/window/blur_event/index.html | 116 ++++ .../web/api/window/cancelanimationframe/index.html | 117 ++++ .../web/api/window/cancelidlecallback/index.html | 107 +++ .../zh-cn/web/api/window/clearimmediate/index.html | 72 ++ .../zh-cn/web/api/window/clearinterval/index.html | 74 +++ files/zh-cn/web/api/window/close/index.html | 77 +++ files/zh-cn/web/api/window/closed/index.html | 59 ++ files/zh-cn/web/api/window/confirm/index.html | 70 ++ files/zh-cn/web/api/window/console/index.html | 49 ++ files/zh-cn/web/api/window/content/index.html | 27 + files/zh-cn/web/api/window/controllers/index.html | 45 ++ files/zh-cn/web/api/window/copy_event/index.html | 72 ++ files/zh-cn/web/api/window/crypto/index.html | 117 ++++ .../zh-cn/web/api/window/customelements/index.html | 61 ++ .../zh-cn/web/api/window/defaultstatus/index.html | 44 ++ .../api/window/deviceorientation_event/index.html | 165 +++++ .../web/api/window/devicepixelratio/index.html | 179 +++++ .../web/api/window/dialogarguments/index.html | 25 + files/zh-cn/web/api/window/directories/index.html | 34 + files/zh-cn/web/api/window/document/index.html | 67 ++ files/zh-cn/web/api/window/dump/index.html | 54 ++ files/zh-cn/web/api/window/error_event/index.html | 133 ++++ files/zh-cn/web/api/window/event/index.html | 84 +++ files/zh-cn/web/api/window/external/index.html | 55 ++ files/zh-cn/web/api/window/find/index.html | 47 ++ files/zh-cn/web/api/window/focus/index.html | 41 ++ files/zh-cn/web/api/window/focus_event/index.html | 120 ++++ files/zh-cn/web/api/window/frameelement/index.html | 73 +++ files/zh-cn/web/api/window/frames/index.html | 56 ++ files/zh-cn/web/api/window/fullscreen/index.html | 48 ++ .../api/window/gamepadconnected_event/index.html | 90 +++ files/zh-cn/web/api/window/getattention/index.html | 33 + .../web/api/window/getcomputedstyle/index.html | 151 +++++ .../api/window/getdefaultcomputedstyle/index.html | 144 ++++ files/zh-cn/web/api/window/getselection/index.html | 82 +++ .../web/api/window/hashchange_event/index.html | 88 +++ files/zh-cn/web/api/window/history/index.html | 34 + files/zh-cn/web/api/window/index.html | 727 +++++++++++++++++++++ files/zh-cn/web/api/window/innerheight/index.html | 122 ++++ files/zh-cn/web/api/window/innerwidth/index.html | 78 +++ .../web/api/window/issecurecontext/index.html | 120 ++++ .../web/api/window/languagechange_event/index.html | 123 ++++ files/zh-cn/web/api/window/length/index.html | 21 + files/zh-cn/web/api/window/localstorage/index.html | 93 +++ files/zh-cn/web/api/window/location/index.html | 305 +++++++++ files/zh-cn/web/api/window/locationbar/index.html | 63 ++ files/zh-cn/web/api/window/matchmedia/index.html | 102 +++ files/zh-cn/web/api/window/menubar/index.html | 57 ++ files/zh-cn/web/api/window/minimize/index.html | 6 + files/zh-cn/web/api/window/moveby/index.html | 34 + files/zh-cn/web/api/window/moveto/index.html | 44 ++ .../api/window/mozanimationstarttime/index.html | 21 + .../web/api/window/mozinnerscreenx/index.html | 44 ++ .../web/api/window/mozinnerscreeny/index.html | 44 ++ .../zh-cn/web/api/window/mozpaintcount/index.html | 21 + files/zh-cn/web/api/window/name/index.html | 66 ++ files/zh-cn/web/api/window/navigator/index.html | 94 +++ .../zh-cn/web/api/window/offline_event/index.html | 63 ++ .../zh-cn/web/api/window/onappinstalled/index.html | 100 +++ .../api/window/onbeforeinstallprompt/index.html | 118 ++++ .../zh-cn/web/api/window/onbeforeunload/index.html | 111 ++++ .../zh-cn/web/api/window/ondevicelight/index.html | 105 +++ .../zh-cn/web/api/window/ondevicemotion/index.html | 57 ++ .../web/api/window/ondeviceorientation/index.html | 47 ++ .../window/ondeviceorientationabsolute/index.html | 35 + .../web/api/window/ondeviceproximity/index.html | 93 +++ files/zh-cn/web/api/window/ondragdrop/index.html | 55 ++ .../web/api/window/ongamepadconnected/index.html | 64 ++ .../api/window/ongamepaddisconnected/index.html | 51 ++ files/zh-cn/web/api/window/onhashchange/index.html | 124 ++++ files/zh-cn/web/api/window/online_event/index.html | 65 ++ files/zh-cn/web/api/window/onmouseup/index.html | 42 ++ .../web/api/window/onmozbeforepaint/index.html | 38 ++ files/zh-cn/web/api/window/onpaint/index.html | 31 + files/zh-cn/web/api/window/onpopstate/index.html | 68 ++ files/zh-cn/web/api/window/onscroll/index.html | 53 ++ files/zh-cn/web/api/window/onunload/index.html | 69 ++ .../web/api/window/onuserproximity/index.html | 45 ++ files/zh-cn/web/api/window/open/index.html | 686 +++++++++++++++++++ files/zh-cn/web/api/window/opendialog/index.html | 71 ++ files/zh-cn/web/api/window/opener/index.html | 38 ++ .../api/window/orientationchange_event/index.html | 73 +++ files/zh-cn/web/api/window/outerheight/index.html | 77 +++ files/zh-cn/web/api/window/outerwidth/index.html | 71 ++ .../zh-cn/web/api/window/pagehide_event/index.html | 98 +++ files/zh-cn/web/api/window/pagexoffset/index.html | 92 +++ files/zh-cn/web/api/window/pageyoffset/index.html | 92 +++ files/zh-cn/web/api/window/parent/index.html | 39 ++ files/zh-cn/web/api/window/performance/index.html | 35 + files/zh-cn/web/api/window/personalbar/index.html | 73 +++ .../zh-cn/web/api/window/popstate_event/index.html | 158 +++++ files/zh-cn/web/api/window/postmessage/index.html | 173 +++++ files/zh-cn/web/api/window/print/index.html | 20 + files/zh-cn/web/api/window/prompt/index.html | 54 ++ .../api/window/rejectionhandled_event/index.html | 72 ++ .../api/window/requestanimationframe/index.html | 123 ++++ .../web/api/window/requestfilesystem/index.html | 74 +++ .../web/api/window/requestidlecallback/index.html | 76 +++ files/zh-cn/web/api/window/resize_event/index.html | 182 ++++++ files/zh-cn/web/api/window/resizeby/index.html | 43 ++ files/zh-cn/web/api/window/resizeto/index.html | 34 + files/zh-cn/web/api/window/restore/index.html | 16 + files/zh-cn/web/api/window/screen/index.html | 32 + files/zh-cn/web/api/window/screenleft/index.html | 88 +++ files/zh-cn/web/api/window/screentop/index.html | 88 +++ files/zh-cn/web/api/window/screenx/index.html | 21 + files/zh-cn/web/api/window/screeny/index.html | 21 + files/zh-cn/web/api/window/scroll/index.html | 70 ++ files/zh-cn/web/api/window/scrollbars/index.html | 65 ++ files/zh-cn/web/api/window/scrollby/index.html | 84 +++ .../zh-cn/web/api/window/scrollbylines/index.html | 56 ++ .../zh-cn/web/api/window/scrollbypages/index.html | 40 ++ files/zh-cn/web/api/window/scrollmaxx/index.html | 45 ++ files/zh-cn/web/api/window/scrollmaxy/index.html | 48 ++ files/zh-cn/web/api/window/scrollto/index.html | 58 ++ files/zh-cn/web/api/window/scrollx/index.html | 34 + files/zh-cn/web/api/window/scrolly/index.html | 131 ++++ files/zh-cn/web/api/window/self/index.html | 22 + .../zh-cn/web/api/window/sessionstorage/index.html | 113 ++++ files/zh-cn/web/api/window/setcursor/index.html | 32 + files/zh-cn/web/api/window/setimmediate/index.html | 54 ++ files/zh-cn/web/api/window/setinterval/index.html | 635 ++++++++++++++++++ files/zh-cn/web/api/window/settimeout/index.html | 476 ++++++++++++++ .../web/api/window/showmodaldialog/index.html | 80 +++ files/zh-cn/web/api/window/sidebar/index.html | 40 ++ .../zh-cn/web/api/window/sizetocontent/index.html | 38 ++ files/zh-cn/web/api/window/stop/index.html | 52 ++ .../zh-cn/web/api/window/storage_event/index.html | 85 +++ files/zh-cn/web/api/window/top/index.html | 55 ++ .../zh-cn/web/api/window/updatecommands/index.html | 37 ++ files/zh-cn/web/api/window/url/index.html | 104 +++ .../zh-cn/web/api/window/visualviewport/index.html | 89 +++ .../zh-cn/web/api/window/window.blur()/index.html | 39 ++ files/zh-cn/web/api/window/window/index.html | 65 ++ 137 files changed, 12021 insertions(+) create mode 100644 files/zh-cn/web/api/window/alert/index.html create mode 100644 files/zh-cn/web/api/window/applicationcache/index.html create mode 100644 files/zh-cn/web/api/window/back/index.html create mode 100644 files/zh-cn/web/api/window/blur_event/index.html create mode 100644 files/zh-cn/web/api/window/cancelanimationframe/index.html create mode 100644 files/zh-cn/web/api/window/cancelidlecallback/index.html create mode 100644 files/zh-cn/web/api/window/clearimmediate/index.html create mode 100644 files/zh-cn/web/api/window/clearinterval/index.html create mode 100644 files/zh-cn/web/api/window/close/index.html create mode 100644 files/zh-cn/web/api/window/closed/index.html create mode 100644 files/zh-cn/web/api/window/confirm/index.html create mode 100644 files/zh-cn/web/api/window/console/index.html create mode 100644 files/zh-cn/web/api/window/content/index.html create mode 100644 files/zh-cn/web/api/window/controllers/index.html create mode 100644 files/zh-cn/web/api/window/copy_event/index.html create mode 100644 files/zh-cn/web/api/window/crypto/index.html create mode 100644 files/zh-cn/web/api/window/customelements/index.html create mode 100644 files/zh-cn/web/api/window/defaultstatus/index.html create mode 100644 files/zh-cn/web/api/window/deviceorientation_event/index.html create mode 100644 files/zh-cn/web/api/window/devicepixelratio/index.html create mode 100644 files/zh-cn/web/api/window/dialogarguments/index.html create mode 100644 files/zh-cn/web/api/window/directories/index.html create mode 100644 files/zh-cn/web/api/window/document/index.html create mode 100644 files/zh-cn/web/api/window/dump/index.html create mode 100644 files/zh-cn/web/api/window/error_event/index.html create mode 100644 files/zh-cn/web/api/window/event/index.html create mode 100644 files/zh-cn/web/api/window/external/index.html create mode 100644 files/zh-cn/web/api/window/find/index.html create mode 100644 files/zh-cn/web/api/window/focus/index.html create mode 100644 files/zh-cn/web/api/window/focus_event/index.html create mode 100644 files/zh-cn/web/api/window/frameelement/index.html create mode 100644 files/zh-cn/web/api/window/frames/index.html create mode 100644 files/zh-cn/web/api/window/fullscreen/index.html create mode 100644 files/zh-cn/web/api/window/gamepadconnected_event/index.html create mode 100644 files/zh-cn/web/api/window/getattention/index.html create mode 100644 files/zh-cn/web/api/window/getcomputedstyle/index.html create mode 100644 files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html create mode 100644 files/zh-cn/web/api/window/getselection/index.html create mode 100644 files/zh-cn/web/api/window/hashchange_event/index.html create mode 100644 files/zh-cn/web/api/window/history/index.html create mode 100644 files/zh-cn/web/api/window/index.html create mode 100644 files/zh-cn/web/api/window/innerheight/index.html create mode 100644 files/zh-cn/web/api/window/innerwidth/index.html create mode 100644 files/zh-cn/web/api/window/issecurecontext/index.html create mode 100644 files/zh-cn/web/api/window/languagechange_event/index.html create mode 100644 files/zh-cn/web/api/window/length/index.html create mode 100644 files/zh-cn/web/api/window/localstorage/index.html create mode 100644 files/zh-cn/web/api/window/location/index.html create mode 100644 files/zh-cn/web/api/window/locationbar/index.html create mode 100644 files/zh-cn/web/api/window/matchmedia/index.html create mode 100644 files/zh-cn/web/api/window/menubar/index.html create mode 100644 files/zh-cn/web/api/window/minimize/index.html create mode 100644 files/zh-cn/web/api/window/moveby/index.html create mode 100644 files/zh-cn/web/api/window/moveto/index.html create mode 100644 files/zh-cn/web/api/window/mozanimationstarttime/index.html create mode 100644 files/zh-cn/web/api/window/mozinnerscreenx/index.html create mode 100644 files/zh-cn/web/api/window/mozinnerscreeny/index.html create mode 100644 files/zh-cn/web/api/window/mozpaintcount/index.html create mode 100644 files/zh-cn/web/api/window/name/index.html create mode 100644 files/zh-cn/web/api/window/navigator/index.html create mode 100644 files/zh-cn/web/api/window/offline_event/index.html create mode 100644 files/zh-cn/web/api/window/onappinstalled/index.html create mode 100644 files/zh-cn/web/api/window/onbeforeinstallprompt/index.html create mode 100644 files/zh-cn/web/api/window/onbeforeunload/index.html create mode 100644 files/zh-cn/web/api/window/ondevicelight/index.html create mode 100644 files/zh-cn/web/api/window/ondevicemotion/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceorientation/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html create mode 100644 files/zh-cn/web/api/window/ondeviceproximity/index.html create mode 100644 files/zh-cn/web/api/window/ondragdrop/index.html create mode 100644 files/zh-cn/web/api/window/ongamepadconnected/index.html create mode 100644 files/zh-cn/web/api/window/ongamepaddisconnected/index.html create mode 100644 files/zh-cn/web/api/window/onhashchange/index.html create mode 100644 files/zh-cn/web/api/window/online_event/index.html create mode 100644 files/zh-cn/web/api/window/onmouseup/index.html create mode 100644 files/zh-cn/web/api/window/onmozbeforepaint/index.html create mode 100644 files/zh-cn/web/api/window/onpaint/index.html create mode 100644 files/zh-cn/web/api/window/onpopstate/index.html create mode 100644 files/zh-cn/web/api/window/onscroll/index.html create mode 100644 files/zh-cn/web/api/window/onunload/index.html create mode 100644 files/zh-cn/web/api/window/onuserproximity/index.html create mode 100644 files/zh-cn/web/api/window/open/index.html create mode 100644 files/zh-cn/web/api/window/opendialog/index.html create mode 100644 files/zh-cn/web/api/window/opener/index.html create mode 100644 files/zh-cn/web/api/window/orientationchange_event/index.html create mode 100644 files/zh-cn/web/api/window/outerheight/index.html create mode 100644 files/zh-cn/web/api/window/outerwidth/index.html create mode 100644 files/zh-cn/web/api/window/pagehide_event/index.html create mode 100644 files/zh-cn/web/api/window/pagexoffset/index.html create mode 100644 files/zh-cn/web/api/window/pageyoffset/index.html create mode 100644 files/zh-cn/web/api/window/parent/index.html create mode 100644 files/zh-cn/web/api/window/performance/index.html create mode 100644 files/zh-cn/web/api/window/personalbar/index.html create mode 100644 files/zh-cn/web/api/window/popstate_event/index.html create mode 100644 files/zh-cn/web/api/window/postmessage/index.html create mode 100644 files/zh-cn/web/api/window/print/index.html create mode 100644 files/zh-cn/web/api/window/prompt/index.html create mode 100644 files/zh-cn/web/api/window/rejectionhandled_event/index.html create mode 100644 files/zh-cn/web/api/window/requestanimationframe/index.html create mode 100644 files/zh-cn/web/api/window/requestfilesystem/index.html create mode 100644 files/zh-cn/web/api/window/requestidlecallback/index.html create mode 100644 files/zh-cn/web/api/window/resize_event/index.html create mode 100644 files/zh-cn/web/api/window/resizeby/index.html create mode 100644 files/zh-cn/web/api/window/resizeto/index.html create mode 100644 files/zh-cn/web/api/window/restore/index.html create mode 100644 files/zh-cn/web/api/window/screen/index.html create mode 100644 files/zh-cn/web/api/window/screenleft/index.html create mode 100644 files/zh-cn/web/api/window/screentop/index.html create mode 100644 files/zh-cn/web/api/window/screenx/index.html create mode 100644 files/zh-cn/web/api/window/screeny/index.html create mode 100644 files/zh-cn/web/api/window/scroll/index.html create mode 100644 files/zh-cn/web/api/window/scrollbars/index.html create mode 100644 files/zh-cn/web/api/window/scrollby/index.html create mode 100644 files/zh-cn/web/api/window/scrollbylines/index.html create mode 100644 files/zh-cn/web/api/window/scrollbypages/index.html create mode 100644 files/zh-cn/web/api/window/scrollmaxx/index.html create mode 100644 files/zh-cn/web/api/window/scrollmaxy/index.html create mode 100644 files/zh-cn/web/api/window/scrollto/index.html create mode 100644 files/zh-cn/web/api/window/scrollx/index.html create mode 100644 files/zh-cn/web/api/window/scrolly/index.html create mode 100644 files/zh-cn/web/api/window/self/index.html create mode 100644 files/zh-cn/web/api/window/sessionstorage/index.html create mode 100644 files/zh-cn/web/api/window/setcursor/index.html create mode 100644 files/zh-cn/web/api/window/setimmediate/index.html create mode 100644 files/zh-cn/web/api/window/setinterval/index.html create mode 100644 files/zh-cn/web/api/window/settimeout/index.html create mode 100644 files/zh-cn/web/api/window/showmodaldialog/index.html create mode 100644 files/zh-cn/web/api/window/sidebar/index.html create mode 100644 files/zh-cn/web/api/window/sizetocontent/index.html create mode 100644 files/zh-cn/web/api/window/stop/index.html create mode 100644 files/zh-cn/web/api/window/storage_event/index.html create mode 100644 files/zh-cn/web/api/window/top/index.html create mode 100644 files/zh-cn/web/api/window/updatecommands/index.html create mode 100644 files/zh-cn/web/api/window/url/index.html create mode 100644 files/zh-cn/web/api/window/visualviewport/index.html create mode 100644 files/zh-cn/web/api/window/window.blur()/index.html create mode 100644 files/zh-cn/web/api/window/window/index.html (limited to 'files/zh-cn/web/api/window') diff --git a/files/zh-cn/web/api/window/alert/index.html b/files/zh-cn/web/api/window/alert/index.html new file mode 100644 index 0000000000..6295c8e7cd --- /dev/null +++ b/files/zh-cn/web/api/window/alert/index.html @@ -0,0 +1,61 @@ +--- +title: window.alert +slug: Web/API/Window/alert +tags: + - alert + - 'alert(`uid = ${uid}`);// alert(`desc ${key}`) !== console.log(`desc `' + - console.log + - key); +translation_of: Web/API/Window/alert +--- +

{{ ApiRef() }}

+ +

概述

+ +

显示一个警告对话框,上面显示有指定的文本内容以及一个"确定"按钮。

+ +

语法

+ +
window.alert(message);
+
+ +
+

 

+ +

alert(`uid = ${uid}`);

+ +

// alert(`desc ${key}`) !== console.log(`desc `, key);

+
+ + + +

示例

+ +
window.alert("Hello world!");
+
+ +

显示如下(不同的浏览器下显示不同):

+ +

Image:AlertHelloWorld.png

+ +

附注

+ +

警告对话框使用在无需用户确认的情况下,否则应该使用其他类型的对话框,比如confirm, prompt.

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.confirm 这里显示的对话框是一个模态窗口,它能阻止用户对浏览器窗口界面的其他部位进行操作,你不应该过多的使用这种模态窗口.

+ +

扩展开发者有时候需要使用nsIPromptService接口来代替该alert方法.

+ +

从Firefox 4开始,在网页中弹出的对话框都换成了标签页范围内的模态窗口,即不会影响其他的标签页,同时还能阻止过多次数的弹窗.

+ +

规范

+ +

{{ DOM0() }}

+ +

相关链接

+ +

confirm, prompt

+ +

扩展开发者应该查看alert()alertCheck()

diff --git a/files/zh-cn/web/api/window/applicationcache/index.html b/files/zh-cn/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..945ab7bd12 --- /dev/null +++ b/files/zh-cn/web/api/window/applicationcache/index.html @@ -0,0 +1,38 @@ +--- +title: window.applicationCache +slug: Web/API/Window/applicationCache +tags: + - HTML5 + - HTML5.1 + - HTML5.2 + - REC +translation_of: Web/API/Window/applicationCache +--- +

{{APIRef}}

+ +

概要

+ +

返回该window 中的应用缓存对象的一个引用。

+ +

语法

+ +
cache = window.applicationCache
+
+ +

参数

+ + + +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/back/index.html b/files/zh-cn/web/api/window/back/index.html new file mode 100644 index 0000000000..ead8d52bb6 --- /dev/null +++ b/files/zh-cn/web/api/window/back/index.html @@ -0,0 +1,26 @@ +--- +title: Window.back() +slug: Web/API/Window/back +translation_of: Web/API/Window/back +--- +
{{APIRef}}
+ +
{{ Non-standard_header() }}
+ +
{{ obsolete_header(31) }}
+ +

总结

+ +

跳转窗口到history中的前一个地址, 这曾是 Gecko 的方法。请使用标准的history.back 替代它。

+ +

Syntax

+ +
window.back()
+ +

Example

+ +
function goBack() {
+   if ( canGoBack ) window.back();
+}
+ +

 

diff --git a/files/zh-cn/web/api/window/blur_event/index.html b/files/zh-cn/web/api/window/blur_event/index.html new file mode 100644 index 0000000000..44cc5ffd7f --- /dev/null +++ b/files/zh-cn/web/api/window/blur_event/index.html @@ -0,0 +1,116 @@ +--- +title: 'Window: blur event' +slug: Web/API/Window/blur_event +translation_of: Web/API/Window/blur_event +--- +
{{APIRef}}
+ +

当元素失去焦点时,blur事件将触发。

+ +

与 blur 相反的是{{domxref("Window/focus_event", "focus")}}。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bubbles(是否支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{DOMxRef("FocusEvent")}}
Event handler property(事件处理程序属性){{domxref("GlobalEventHandlers/onblur", "onblur")}}
Sync / Async(同步/异步)Sync
ComposedYes
+ +

示例

+ +

在线示例

+ +

此示例当文档失去焦点时,更改其外观。它使用{{domxref("EventTarget.addEventListener()","addEventListener()")}} 去监听{{domxref("Window/focus_event", "focus")}}和 blur 事件。

+ +

HTML

+ +
<p id="log">Click on this document to give it focus.</p>
+ +

CSS

+ +
.paused {
+  background: #ddd;
+  color: #555;
+}
+ +

JavaScript

+ +
function pause() {
+  document.body.classList.add('paused');
+  log.textContent = 'FOCUS LOST!';
+}
+
+function play() {
+  document.body.classList.remove('paused');
+  log.textContent = 'This document has focus. Click outside the document to lose focus.';
+}
+
+const log = document.getElementById('log');
+
+window.addEventListener('blur', pause);
+window.addEventListener('focus', play);
+ +

结果

+ +

{{EmbedLiveSample("在线示例")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("UI Events", "#event-type-blur")}}{{Spec2("UI Events")}}Added info that this event is composed.
{{SpecName("DOM3 Events", "#event-type-blur")}}{{Spec2("DOM3 Events")}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.blur_event")}}

+ +

{{DOMxRef(" document. activeelement ")}}的值在处理({{bug(452307)}})时因浏览器而异 ;({{bug(452307)}}):IE10将其设置为焦点将移动到的元素,而Firefox和Chrome通常将其设置为文档的 body。

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/cancelanimationframe/index.html b/files/zh-cn/web/api/window/cancelanimationframe/index.html new file mode 100644 index 0000000000..0d98e5db24 --- /dev/null +++ b/files/zh-cn/web/api/window/cancelanimationframe/index.html @@ -0,0 +1,117 @@ +--- +title: window.cancelAnimationFrame +slug: Web/API/Window/cancelAnimationFrame +translation_of: Web/API/Window/cancelAnimationFrame +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

概述

+ +

取消一个先前通过调用{{ domxref("window.requestAnimationFrame()") }}方法添加到计划中的动画帧请求.

+ +

语法

+ +
window.mozCancelAnimationFrame(requestID);               // Firefox
+
+ +

参数

+ +
+
requestID
+
先前调用{{ domxref("window.requestAnimationFrame()") }}方法时返回的ID.
+
+ +

示例

+ +
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
+                            window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
+
+var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
+
+var start = window.mozAnimationStartTime;  // 只有Firefox支持mozAnimationStartTime属性,其他浏览器可以使用Date.now()来替代.
+
+var myReq;
+function step(timestamp) {
+  var progress = timestamp - start;
+  d.style.left = Math.min(progress/10, 200) + "px";
+  if (progress < 2000) {
+    myReq = requestAnimationFrame(step);
+  }
+}
+myReq = requestAnimationFrame(step);
+
+window.cancelAnimationFrame(myReq);
+
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

21.0 {{ property_prefix("webkit") }}

+ +

24.0 脱前缀

+
+

{{ CompatGeckoDesktop("11.0") }} {{ property_prefix("moz") }} 

+
10{{ CompatUnknown() }} +

6.0 {{ property_prefix("webkit") }}

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }} +

{{ CompatUnknown() }}

+
{{ CompatGeckoMobile("11.0") }} {{ property_prefix("moz") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

规范

+ +

{{ spec("http://www.w3.org/TR/animation-timing/#cancelAnimationFrame", "Timing control for script-based animations: cancelAnimationFrame", "WD") }}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/cancelidlecallback/index.html b/files/zh-cn/web/api/window/cancelidlecallback/index.html new file mode 100644 index 0000000000..79abf32d93 --- /dev/null +++ b/files/zh-cn/web/api/window/cancelidlecallback/index.html @@ -0,0 +1,107 @@ +--- +title: window.cancelIdleCallback() +slug: Web/API/Window/cancelIdleCallback +tags: + - API + - JavaScript timers + - Window + - cancelIdleCallback +translation_of: Web/API/Window/cancelIdleCallback +--- +
{{APIRef}}{{SeeCompatTable}}
+ +

概述

+ +

 window.cancelIdleCallback() 方法用于取消之前调用{{domxref("window.requestIdleCallback()")}} 的回调。

+ +

语法

+ +
window.cancelIdleCallback(handle);
+ +

参数

+ +
+
handle
+
调用 {{domxref("window.requestIdleCallback()")}}  时返回的 ID.
+
+ +

返回值

+ +

undefined.

+ +

示例

+ +

在文章 Cooperative Scheduling of Background Tasks API 中可以查看 完整示例 。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatGeckoDesktop(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(47)}}{{CompatChrome(47)}}{{CompatGeckoMobile(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Idle callback 在  Firefox 53 中增加, 默认是禁用状态,设置  dom.requestIdleCallback.enabled 为 true启用。 Idle callbacks 再 Firefox 55及之后版本中默认启用。

diff --git a/files/zh-cn/web/api/window/clearimmediate/index.html b/files/zh-cn/web/api/window/clearimmediate/index.html new file mode 100644 index 0000000000..84d84226e6 --- /dev/null +++ b/files/zh-cn/web/api/window/clearimmediate/index.html @@ -0,0 +1,72 @@ +--- +title: window.clearImmediate +slug: Web/API/Window/clearImmediate +translation_of: Web/API/Window/clearImmediate +--- +

{{ ApiRef() }}

+

概述

+

此方法用来清除 {{ domxref("window.setImmediate") }}.

+
+ 注意: 注意: 该方法最近刚刚被微软提出, 可能不会被w3c批准成为标准, 目前只有最新版Internet Explorer实现了该方法.
+

语法

+
window.clearImmediate(immediateID)
+
+

这里的immediateID是由{{ domxref("window.setImmediate") }}返回的.

+

例子

+
var immediateID = setImmediate(function () {
+  // Run some code
+}
+
+document.getElementById("button").addEventListener(function () {
+  clearImmediate(immediateID);
+}, false);
+
+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+

相关链接

+

{{ domxref("window.setImmediate") }}

+

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

diff --git a/files/zh-cn/web/api/window/clearinterval/index.html b/files/zh-cn/web/api/window/clearinterval/index.html new file mode 100644 index 0000000000..9a2d6e1790 --- /dev/null +++ b/files/zh-cn/web/api/window/clearinterval/index.html @@ -0,0 +1,74 @@ +--- +title: WindowTimers.clearInterval() +slug: Web/API/Window/clearInterval +tags: + - API + - WindowOrWorkerGlobalScope + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{ApiRef("HTML DOM")}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} mixin 的 clearInterval() 方法可取消先前通过 {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 设置的重复定时任务。

+ +

语法

+ +
scope.clearInterval(intervalID)
+
+ +

Parameters

+ +
+
intervalID
+
要取消的定时器的 ID。是由 setInterval() 返回的。
+
+ +

值得一提的是,{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 和 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} 共用其定义的 IDs,即可以使用 clearInterval() 和 {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} 中的任意一个。然而,为了使代码可读性更强,你应该尽量避免这种用法。

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

查看 setInterval() 的示例

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.clearInterval")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/close/index.html b/files/zh-cn/web/api/window/close/index.html new file mode 100644 index 0000000000..d9904dd794 --- /dev/null +++ b/files/zh-cn/web/api/window/close/index.html @@ -0,0 +1,77 @@ +--- +title: Window.close() +slug: Web/API/Window/close +tags: + - API + - DOM + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/close +--- +
{{APIRef}}
+ +

Window.close() 方法关闭当前窗口或某个指定的窗口。

+ +

该方法只能由 {{domxref("Window.open()")}} 方法打开的窗口的 window 对象来调用。如果一个窗口不是由脚本打开的,那么,在调用该方法时,JavaScript 控制台会出现类似下面的错误:不能使用脚本关闭一个不是由脚本打开的窗口。Scripts may not close windows that were not opened by script.

+ +

同时也要注意,对于由 HTMLIFrame​Element​.content​Window 返回的 {{domxref("Window")}} 对象,close() 也没有效果。

+ +

语法

+ +
window.close();
+ +

例子

+ +

关闭一个由 window.open()方法打开的窗口

+ +

这个例子展示了如何使用这个方法关闭使用 {{domxref("window.open()")}} 打开的窗口

+ +
// 用于存储将要打开的窗口(的引用)的全局变量
+var openedWindow;
+
+function openWindow() {
+  openedWindow = window.open('moreinfo.htm');
+}
+
+function closeOpenedWindow() {
+  openedWindow.close();
+}
+
+ +

关闭当前窗口

+ +

当直接调用 window 对象的 close() 方法而非在一个 window 实例上调用 close() 时,浏览器会关闭最前面的窗口,无论是不是你的脚本创建的这个窗口。(Firefox 35.0.1:脚本不能关闭不是他打开的窗口)

+ +
function closeCurrentWindow() {
+  window.close();
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-window-close', 'window.close()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', "browsers.html#dom-window-close", "Window.close()")}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.close")}}

diff --git a/files/zh-cn/web/api/window/closed/index.html b/files/zh-cn/web/api/window/closed/index.html new file mode 100644 index 0000000000..084eeaa92e --- /dev/null +++ b/files/zh-cn/web/api/window/closed/index.html @@ -0,0 +1,59 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +translation_of: Web/API/Window/closed +--- +
{{APIRef}}
+ +

概述

+ +

此只读属性表示所引用的窗口是否关闭。

+ +

语法

+ +
isClosed = windowRef.closed;
+
+ +
+
isClosed
+
一个布尔值。 可能的值: +
    +
  • true: 窗口已被关闭。
  • +
  • false: 窗口是打开的。
  • +
+
+
+ +

示例

+ +

更改一个弹出窗口的URL

+ +

下面的示例演示怎样更改一个已打开的弹出窗口的URL。尝试更改URL之前,它使用window.opener属性来检查有窗口被打开,并且该窗口没有关闭:

+ +
// Check that an opener exists and is not closed
+if (window.opener && !window.opener.closed) {
+  window.opener.location.href = "http://www.mozilla.org";
+}
+ +

请注意,弹出窗口只能访问打开他们的窗口。

+ +

刷新先前打开的弹出窗口

+ +

在这个例子中,函数refreshPopupWindow()调用重载方法的弹出的位置要刷新其数据的对象。如果弹出窗口尚未打开,或者用户已关闭它打开一个新窗口。

+ +
var popupWindow = null;
+
+function refreshPopupWindow() {
+  if (popupWindow && !popupWindow.closed) {
+    // popupWindow is open, refresh it
+    popupWindow.location.reload(true);
+  } else {
+    // Open a new popup window
+    popupWindow = window.open("popup.html","dataWindow");
+  }
+}
+
+ +

技术说明

+ +

HTML5

diff --git a/files/zh-cn/web/api/window/confirm/index.html b/files/zh-cn/web/api/window/confirm/index.html new file mode 100644 index 0000000000..5f021b77e9 --- /dev/null +++ b/files/zh-cn/web/api/window/confirm/index.html @@ -0,0 +1,70 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +tags: + - API + - DOM + - React-Router + - Window + - Window.confirm() +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

Window.confirm() 方法显示一个具有一个可选消息和两个按钮(确定和取消)的模态对话框 。

+ +

语法

+ +
result = window.confirm(message);
+
+ + + +

示例

+ +
if (window.confirm("Do you really want to leave?")) {
+  window.open("exit.html", "Thanks for Visiting!");
+}
+
+ +

运行结果: 

+ +

firefox confirm
+  

+ +

注意事项:

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert对话框是弹出式(modal)的(也即alert样式, 译者注). 直到这个对话框被点击后, 后面的脚本才会运行. 请勿滥用此功能, 这里列出了很多个理由: 请放弃使用对话框来确认信息.

+ +

Mozilla Chrome 的用户(比如Firefox插件开发者)应该使用{{interface("nsIPromptService")}}这个方法.

+ +

Chrome浏览器版本 {{CompatChrome(46.0)}} 开始屏蔽内部{{htmlelement("iframe")}}元素, 除非用户在沙箱内开启了allow-modal选项.

+ +

在{{gecko_minversion_inline("23.0")}}内核中, 参数是可选的.

+ +

兼容性

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML5 Web application', '#dom-confirm', 'confirm()')}}{{Spec2('HTML5 Web application')}}Initial definition.
+ +

更多

+ + diff --git a/files/zh-cn/web/api/window/console/index.html b/files/zh-cn/web/api/window/console/index.html new file mode 100644 index 0000000000..3e00d38643 --- /dev/null +++ b/files/zh-cn/web/api/window/console/index.html @@ -0,0 +1,49 @@ +--- +title: Window.console +slug: Web/API/Window/console +translation_of: Web/API/Window/console +--- +

{{ APIRef }}

+ +

只读属性Window.console返回一个对{{domxref("Console")}}对象的引用,Window.console提供了向浏览器控制台输出日志信息的方法。这些方法仅应该用于调试,并不应该用来给最终用户呈现信息。

+ +

语法

+ +
var consoleObj = window.console;
+
+ +

示例

+ +

输出信息

+ +

第一个例子向控制台输出文字。

+ +
console.log("An error occurred while loading the content");
+
+ +

下边这个例子向控制台打印一个对象,可以通过点击展开组件查看对象的各项属性。

+ +
console.dir(someObject);
+ +

更多示例参考 {{SectionOnPage("/en-US/docs/Web/API/Console", "Usage")}}。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +
+

当前各种浏览器之间的实现还有很多差异,推动一致的工作也在进行当中。

+
diff --git a/files/zh-cn/web/api/window/content/index.html b/files/zh-cn/web/api/window/content/index.html new file mode 100644 index 0000000000..d3d3f4be3d --- /dev/null +++ b/files/zh-cn/web/api/window/content/index.html @@ -0,0 +1,27 @@ +--- +title: window.content +slug: Web/API/Window/content +translation_of: Web/API/Window/content +--- +

{{ ApiRef() }}

+

概述

+

返回主内容窗口的Window对象.该属性只在包含有属性type="content-primary"<browser> (或者 tabbrowser 或者 <iframe>)标签的XUL窗口下才会用到.最常用到的地方就是Firefox的主窗口, browser.xul. 在这种情况下, content 返回一个浏览器中的当前页面的Window对象的引用.相当于browserRef.contentWindow的快捷方式.

+

在一个非特权的内容窗口中 (网页), content 等同于普通的 top (除非网页是在侧边栏中加载的, content仍然会指向当前标签页中的Window对象).

+

一些旧的代码示例中使用了 _content 而不是 content.该形式的属性名已经被废弃很久了,你应该在新的代码中使用content.

+

语法

+
var windowObject = window.content;
+
+

例子

+

在一个拥有<browser type="content-primary"/>标签的chrome XUL 窗口下运行下面的代码.会在浏览器当前显示的页面上的第一个div标签上添加一个红色的边框:

+
content.document.getElementsByTagName("div")[0].style.border = "solid red 1px";
+
+

规范

+

不属于W3C规范.

+

相关链接

+ +
+  
+

{{ languages( { "fr": "fr/DOM/window.content", "ja": "ja/DOM/window.content", "pl": "pl/DOM/window.content" } ) }}

diff --git a/files/zh-cn/web/api/window/controllers/index.html b/files/zh-cn/web/api/window/controllers/index.html new file mode 100644 index 0000000000..972c1fd452 --- /dev/null +++ b/files/zh-cn/web/api/window/controllers/index.html @@ -0,0 +1,45 @@ +--- +title: Window.controllers +slug: Web/API/Window/controllers +tags: + - API + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - XUL + - 参考 + - 属性 + - 窗口 + - 非标准 +translation_of: Web/API/Window/controllers +--- +
{{APIRef}}{{non-standard_header}}
+ +

{{domxref("Window")}} 接口的 controllers 属性返回 chorme 窗口的 XUL 控制器。

+ +

语法

+ +
controllers = window.controllers
+
+ + + +

规范

+ +

XUL-专有属性,不属于任何规范。

+ +
+

默认情况下,窗口的控制器包含支持全局窗口命令的代码。

+ +

chrome 代码可以添加控制器(与 globalOverlay.js 中的 goDoCommandgoUpdateCommand 函数配合使用)。

+ +

然而,浏览器窗口被关闭时,我们必须手动删除这些添加的控制器,因为浏览器并不会自动完成这些操作。

+ +

如果有忘记删除的控制器,则会导致错误:

+bug 415775: + +
ASSERTION: XPConnect is being called on a scope without a 'Components' property!
+
diff --git a/files/zh-cn/web/api/window/copy_event/index.html b/files/zh-cn/web/api/window/copy_event/index.html new file mode 100644 index 0000000000..b2797de03e --- /dev/null +++ b/files/zh-cn/web/api/window/copy_event/index.html @@ -0,0 +1,72 @@ +--- +title: 'Window: copy event' +slug: Web/API/Window/copy_event +tags: + - API + - Clippboard API + - copy +translation_of: Web/API/Window/copy_event +--- +
{{APIRef}}
+ +

当用户通过浏览器的用户界面启动复制操作时,将触发 copy 事件。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)Yes
Cancelable(可撤销)Yes
Interface(接口){{domxref("ClipboardEvent")}}
Event handler property(事件处理程序属性){{domxref("HTMLElement/oncopy", "oncopy")}}
+ +

此事件的原始目标是 {{domxref("Element")}} 它是复制操作的预期目标。您可以在 {{domxref("Window")}} 界面上监听此事件,以在捕获或冒泡阶段对其进行处理。 有关此事件的完整详细信息,请参见 Element: copy event.

+ +

示例

+ +
window.addEventListener('copy', (event) => {
+    console.log('copy action initiated')
+});
+ +

规范

+ + + + + + + + + + + + + + +
规范状态
{{SpecName('Clipboard API', '#clipboard-event-copy')}}{{Spec2('Clipboard API')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.copy_event")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/crypto/index.html b/files/zh-cn/web/api/window/crypto/index.html new file mode 100644 index 0000000000..d8a732b86e --- /dev/null +++ b/files/zh-cn/web/api/window/crypto/index.html @@ -0,0 +1,117 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +translation_of: Web/API/Window/crypto +--- +
{{APIRef}}
+ +

Window.crypto只读属性返回与全局对象关联的 {{domxref("Crypto")}}对象。 此对象允许网页访问某些加密相关服务。

+ +

语法

+ +
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
+
+ +

范例

+ +

使用 {{domxref("Window.crypto")}} 来访问getRandomValues() 方法.

+ +

JavaScript

+ +
genRandomNumbers = function getRandomNumbers() {
+  var array = new Uint32Array(10);
+  window.crypto.getRandomValues(array);
+
+  var randText = document.getElementById("myRandText");
+  randText.innerHTML = "The random numbers are: "
+  for (var i = 0; i < array.length; i++) {
+    randText.innerHTML += array[i] + " ";
+  }
+}
+
+ +

HTML

+ +
<p id="myRandText">随机数字: </p>
+<button type="button" onClick='genRandomNumbers()'>生成10个随机数字</button>
+ +

结果

+ +

{{ EmbedLiveSample('Example') }}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态批注
{{SpecName("Web Crypto API", "#dfn-GlobalCrypto", "Window.crypto")}}{{Spec2("Web Crypto API")}}Initial definition
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support44 {{CompatVersionUnknown}}{{CompatVersionUnknown}}11 {{property_prefix("ms")}}2019{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidFirefox MobileFirefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

另见

+ + diff --git a/files/zh-cn/web/api/window/customelements/index.html b/files/zh-cn/web/api/window/customelements/index.html new file mode 100644 index 0000000000..c53e5f8b48 --- /dev/null +++ b/files/zh-cn/web/api/window/customelements/index.html @@ -0,0 +1,61 @@ +--- +title: Window.customElements +slug: Web/API/Window/customElements +tags: + - API + - CustomElementRegistry + - Property + - Reference + - Web Components + - Window + - custom elements + - customElements +translation_of: Web/API/Window/customElements +--- +
{{APIRef}}
+ +

customElements 是{{domxref("Window")}}对象上的一个只读属性,接口返回一个{{domxref("CustomElementRegistry")}} 对象的引用,可用于注册新的 custom elements,或者获取之前定义过的自定义元素的信息。

+ +

例子

+ +

这个属性最常用的例子是用来获取使用{{domxref("CustomElementRegistry.define()")}}方法定义和注册的自定义元素,例如:

+ +
let customElementRegistry = window.customElements;
+customElementRegistry.define('my-custom-element', MyCustomElement);
+ +

However, it is usually shortened to something like the following:

+ +
customElements.define('element-details',
+  class extends HTMLElement {
+    constructor() {
+      super();
+      const template = document
+        .getElementById('element-details-template')
+        .content;
+      const shadowRoot = this.attachShadow({mode: 'open'})
+        .appendChild(template.cloneNode(true));
+  }
+});
+ +

参阅我们的 web-components-examples 获取更多有用的例子。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName("HTML WHATWG", "custom-elements.html#dom-window-customelements", "window.customElements")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Window.customElements")}}

diff --git a/files/zh-cn/web/api/window/defaultstatus/index.html b/files/zh-cn/web/api/window/defaultstatus/index.html new file mode 100644 index 0000000000..97e48af30e --- /dev/null +++ b/files/zh-cn/web/api/window/defaultstatus/index.html @@ -0,0 +1,44 @@ +--- +title: Window.defaultStatus +slug: Web/API/Window/defaultStatus +tags: + - HTML DOM对象 + - 接口 +translation_of: Web/API/Window/defaultStatus +--- +

{{ obsolete_header(23) }}

+ +

{{ APIRef() }}

+ +

Summary

+ +

获取或设置给定窗口的状态栏文本。

+ +

Syntax

+ +
var sMsg = window.defaultStatus;
+window.defaultStatus = sMsg;
+
+ +

Parameters

+ + + +

Example

+ +
<html>
+ <body onload="window.defaultStatus='hello!';"/>
+  <button onclick="window.confirm('你确定要退出?');">confirm</button>
+ </body>
+</html>
+
+ +

Notes

+ +

页面HTML加载完成后要设置状态栏内容可以使用  window.status.

+ +

Specification

+ +

HTML5

diff --git a/files/zh-cn/web/api/window/deviceorientation_event/index.html b/files/zh-cn/web/api/window/deviceorientation_event/index.html new file mode 100644 index 0000000000..4b36867f04 --- /dev/null +++ b/files/zh-cn/web/api/window/deviceorientation_event/index.html @@ -0,0 +1,165 @@ +--- +title: deviceorientation +slug: Web/API/Window/deviceorientation_event +translation_of: Web/API/Window/deviceorientation_event +--- +

deviceorientation 事件在方向传感器输出新数据的时候触发。其数据系传感器与地球坐标系相比较所得,也就是说在设备上可能会采用设备地磁计的数据。详情参考有关方向与运动信息的说明(Orientation and motion data explained)

+ +

常规信息

+ +
+
标准
+
Orientation
+
接口
+
DeviceOrientationEvent
+
冒泡
+
+
可取消
+
+
Target
+
DefaultView (window)
+
默认操作
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not?
alpha {{readonlyInline}}double (float)The current orientation of the device around the Z axis; that is, how far the device is rotated around a line perpendicular to the device.
beta {{readonlyInline}}double (float)The current orientation of the device around the X axis; that is, how far the device is tipped forward or backward.
gamma {{readonlyInline}}double (float)The current orientation of the device around the Y axis; that is, how far the device is turned left or right.
absolute {{readonlyInline}}{{jsxref("boolean")}}This value is true if the orientation is provided as a difference between the device coordinate frame and the Earth coordinate frame; if the device can't detect the Earth coordinate frame, this value is false.
+ +

例子

+ +
if (window.DeviceOrientationEvent) {
+    window.addEventListener("deviceorientation", function(event) {
+        // alpha: 在Z轴上的角度
+        var rotateDegrees = event.alpha;
+        // gamma: 从左到右
+        var leftToRight = event.gamma;
+        // beta: 从前到后的运动
+        var frontToBack = event.beta;
+
+        handleOrientationEvent(frontToBack, leftToRight, rotateDegrees);
+    }, true);
+}
+
+var handleOrientationEvent = function(frontToBack, leftToRight, rotateDegrees) {
+    // 弹奏一曲夏威夷吉他
+};
+
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本功能支持7.03.6[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本功能支持3.03.6[1]{{CompatNo}}124.2
+
+ +

[1] Firefox 3.6, 4, 和 5 支持 mozOrientation 这一类似 DeviceOrientation 的事件。

+ +

相关事件

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/devicepixelratio/index.html b/files/zh-cn/web/api/window/devicepixelratio/index.html new file mode 100644 index 0000000000..a5976667d9 --- /dev/null +++ b/files/zh-cn/web/api/window/devicepixelratio/index.html @@ -0,0 +1,179 @@ +--- +title: Window.devicePixelRatio +slug: Web/API/Window/devicePixelRatio +translation_of: Web/API/Window/devicePixelRatio +--- +

{{APIRef}}

+ +

{{domxref("Window")}} 接口的devicePixelRatio返回当前显示设备的物理像素分辨率与CSS像素分辨率之比。 此值也可以解释为像素大小的比率:一个CSS像素的大小与一个物理像素的大小。 简单来说,它告诉浏览器应使用多少屏幕实际像素来绘制单个CSS像素。

+ +

当处理标准显示器与HiDPI或Retina显示器之间的差异时,这很有用,后者使用更多的屏幕像素绘制相同的对象,从而获得更清晰的图像。

+ +

您可以使用{{domxref("Window.matchMedia", "window.matchMedia()")}} 检查devicePixelRatio的值是否发生更改(例如,如果用户将窗口拖动到带有 不同的像素密度)。 请参阅{{anch("Monitoring screen resolution or zoom level changes", "下面的例子")}}.。

+ +

语法

+ +
value = window.devicePixelRatio;
+
+ +

值Value

+ +

一个双精度浮点值,指示显示器的物理像素分辨率与CSS像素分辨率之比。 值1表示经典96 DPI(在某些平台上为76 DPI)显示,而对于HiDPI / Retina显示屏则期望值为2。 在异常低分辨率的显示器中,或更常见的是,当屏幕的像素深度比简单地将96或76 DPI的标准分辨率提高一倍时,可能还会返回其他值。

+ +

例子

+ +

在 <canvas> 中更正分辨率

+ +

{{htmlelement("canvas")}}可能在视网膜屏幕上显得太模糊。 使用window.devicePixelRatio确定应添加多少额外的像素密度以使图像更清晰。

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Set display size (css pixels).
+var size = 200;
+canvas.style.width = size + "px";
+canvas.style.height = size + "px";
+
+// Set actual size in memory (scaled to account for extra pixel density).
+var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
+canvas.width = Math.floor(size * scale);
+canvas.height = Math.floor(size * scale);
+
+// Normalize coordinate system to use css pixels.
+ctx.scale(scale, scale);
+
+ctx.fillStyle = "#bada55";
+ctx.fillRect(10, 10, 300, 300);
+ctx.fillStyle = "#ffffff";
+ctx.font = '18px Arial';
+ctx.textAlign = 'center';
+ctx.textBaseline = 'middle';
+
+var x = size / 2;
+var y = size / 2;
+
+var textString = "I love MDN";
+ctx.fillText(textString, x, y);
+ +

This image describe the impact of different value on retina display.

+ +

监视屏幕分辨率或缩放级别的更改

+ +

在此示例中,我们将设置一个媒体查询并观看它以查看设备分辨率何时更改,以便我们可以检查devicePixelRatio的值来处理所需的任何更新。

+ +

JavaScript

+ +

JavaScript代码创建媒体查询,以监控设备分辨率并在每次更改时检查devicePixelRatio的值。

+ +
let pixelRatioBox = document.querySelector(".pixel-ratio");
+let mqString = `(resolution: ${window.devicePixelRatio}dppx)`;
+
+const updatePixelRatio = () => {
+  let pr = window.devicePixelRatio;
+  let prString = (pr * 100).toFixed(0);
+  pixelRatioBox.innerText = `${prString}% (${pr.toFixed(2)})`;
+}
+
+updatePixelRatio();
+
+matchMedia(mqString).addListener(updatePixelRatio);
+
+ +

字符串mqString设置为媒体查询本身。 媒体查询以(resolution: 1dppx)(对于标准显示)或(resolution: 2dppx)(对于Retina / HiDPI显示)开始,检查当前显示分辨率是否与每个像素px的实际设备像素点匹配。

+ +

updatePixelRatio()函数获取devicePixelRatio的当前值,然后将pixelRatioBox的 {{domxref("HTMLElement.innerText", "innerText")}}设置为一个字符串,该字符串同时显示百分比和原始十进制值比率,最多两位小数。

+ +

然后,调用updatePixelRatio()函数一次以显示起始值,然后使用{{domxref("Window.matchMedia", "matchMedia()")}} 和 {{domxref("EventTarget.addEventListener", "addEventListener()")}}来将updatePixelRatio()设置为change事件的处理程序。

+ +

HTML

+ +

HTML将创建包含说明的框和将显示当前像素比率信息的pixel-ratio 框。

+ +
<div class="container">
+  <div class="inner-container">
+    <p>This example demonstrates the effect of zooming the page in
+       and out (or moving it to a screen with a different scaling
+       factor) on the value of the property <code>Window.devicePixelRatio</code>.
+       Try it and watch what happens!</p>
+  </div>
+    <div class="pixel-ratio"></div>
+</div>
+ +
+

CSS

+
+ +
body {
+  font: 22px arial, sans-serif;
+}
+
+.container {
+  top: 2em;
+  width: 22em;
+  height: 14em;
+  border: 2px solid #22d;
+  margin: 0 auto;
+  padding: 0;
+  background-color: #a9f;
+}
+
+.inner-container {
+  padding: 1em 2em;
+  text-align: justify;
+  text-justify: auto;
+}
+
+.pixel-ratio {
+  position: relative;
+  margin: auto;
+  height: 1.2em;
+  text-align: right;
+  bottom: 0;
+  right: 1em;
+  font-weight: bold;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Monitoring_screen_resolution_or_zoom_level_changes", "100%", 500)}}

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-window-devicepixelratio", "Window.devicePixelRatio")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器兼容性

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("api.Window.devicePixelRatio")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/dialogarguments/index.html b/files/zh-cn/web/api/window/dialogarguments/index.html new file mode 100644 index 0000000000..d26d56a819 --- /dev/null +++ b/files/zh-cn/web/api/window/dialogarguments/index.html @@ -0,0 +1,25 @@ +--- +title: Window.dialogArguments +slug: Web/API/Window/dialogArguments +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Property + - Reference + - Window +translation_of: Web/API/Window/dialogArguments +--- +

{{ Fx_minversion_header(3) }} {{ deprecated_header() }}{{APIRef}}

+ +

摘要

+ +

dialogArguments 属性返回{{domxref("window.showModalDialog()")}} 方法传递的参数。 这可以让你确定在创建模态对话框时指定了哪些参数。

+ +

语法

+ +
value = window.dialogArguments;
diff --git a/files/zh-cn/web/api/window/directories/index.html b/files/zh-cn/web/api/window/directories/index.html new file mode 100644 index 0000000000..ea480aa14d --- /dev/null +++ b/files/zh-cn/web/api/window/directories/index.html @@ -0,0 +1,34 @@ +--- +title: Window.directories +slug: Web/API/Window/directories +translation_of: Web/API/Window/directories +--- +

{{ obsolete_header("2.0") }}

+ +

{{ APIRef() }}

+ +

概述

+ +

用于返回 window 下的 personalbar toolbar 对象, 已经过时,请使用 {{ domxref("window.personalbar") }} 来代替该属性。

+ +

语法

+ +
var dirBar = window.directories;
+
+ +

参数

+ +

dirBar 是 BarProp 类型的对象。

+ +

例子

+ +
<script>
+ function dirs() {
+  alert(window.directories);
+ }
+</script>
+
+ +

规范

+ +

不属于任何规范。

diff --git a/files/zh-cn/web/api/window/document/index.html b/files/zh-cn/web/api/window/document/index.html new file mode 100644 index 0000000000..04258782b7 --- /dev/null +++ b/files/zh-cn/web/api/window/document/index.html @@ -0,0 +1,67 @@ +--- +title: window.document +slug: Web/API/Window/document +translation_of: Web/API/Window/document +--- +

{{ ApiRef() }}

+ +

window.document返回当前窗口内的文档节点({{domxref("document")}})

+ +
注: {{ Fx_minversion_inline(3) }}从Firefox 3和IE7开始,访问其他页面内的文档节点会受到同源策略的影响.
+ +

语法

+ +
doc = window.document
+
+ +

参数

+ + + +

例子

+ +
<!DOCTYPE html>
+<html>
+<head>
+   <title>Hello, World!</title>
+</head>
+<body>
+
+<script type="text/javascript">
+   var doc = window.document;
+   alert( doc.title);    // 弹出: Hello, World!
+</script>
+
+</body>
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-2', 'Window.document')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-document-0', 'Window.document')}}{{Spec2('HTML5 W3C')}}
+ + +

浏览器兼容性

+ + + +

{{Compat("api.Window.document")}}

diff --git a/files/zh-cn/web/api/window/dump/index.html b/files/zh-cn/web/api/window/dump/index.html new file mode 100644 index 0000000000..41d0a286bf --- /dev/null +++ b/files/zh-cn/web/api/window/dump/index.html @@ -0,0 +1,54 @@ +--- +title: Window.dump() +slug: Web/API/Window/dump +tags: + - API + - DOM + - DOM_0 + - Method + - Non-standard +translation_of: Web/API/Window/dump +--- +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +

概要

+ +

将信息打印到 (本地) 控制台(console).

+ +

语法

+ +
window.dump(message);
+
+dump(message);
+
+ + + +

注解

+ +

dump()常见用途是调试JavaScript。dump如果使用console选项启动了Firefox进程,则将消息发送到系统控制台(本地控制台)如果console未指定选项,则输出到对应终端。dump()的输出不会发送到浏览器控制台输出可以使用console.log()发送到浏览器控制台特殊的代码还能将消息记录到错误控制台 / 浏览器控制台Components.utils.reportErrornsIConsoleService

+ +

dump()也可用于使用JavaScript实现的XPCOM组件,尽管 {{domxref("window")}} 不是组件中的全局对象。它也明确地在沙箱中提供但是,这种使用dump不受下面提到的偏好的影响---它将始终显示出来。因此,建议您自己检查此偏好或使用自己的调试偏好,以确保在根本不感兴趣的情况下,不会向用户的控制台发送大量调试内容。请注意,dumpXPCOM组件的输出将转到stderr,而dump 其他地方将输出stdout

+ +

Gecko 默认情况dump()下被禁用 - 它不会做任何事情,但也不会引起错误。要查看dump输出,您必须通过设置首选项browser.dom.window.dump.enabled启用它您可以在about:configuser.js文件中设置首选项注意:about:config默认情况下不会列出此首选项,您可能需要创建它(右键单击内容区域 - >新建 - >布尔值)。

+ +

在Windows上,您需要一个控制台才能看到任何东西。如果您还没有,请关闭应用程序并使用命令行参数重新打开console应该创建控制台或使用-attach-console现有的控制台。在其他操作系统上,从终端启动应用程序就足够了。

+ +

要将控制台输出重定向到文件,请运行firefox 而不使用-console选项,并使用语法将stderr和stdout重定向到一个文件,即:

+ +
firefox > console.txt 2>&1
+
+ +
+

如果您希望控制台消息出现在用于启动应用程序的控制台中,则可以使用Gecko控制台重定向器预编译的二进制文件可以在压缩的归档文件  https://github.com/matthewkastor/Redirector/archive/master.zip中找到Redirector-master\Gecko\Console Redirector\bin\Release将所有dll和exe复制到任何你想要的地方。然后跑Console Redirector.exe /?

+
+ +

Specification

+ +

这不是标准的一部分

diff --git a/files/zh-cn/web/api/window/error_event/index.html b/files/zh-cn/web/api/window/error_event/index.html new file mode 100644 index 0000000000..893466b46d --- /dev/null +++ b/files/zh-cn/web/api/window/error_event/index.html @@ -0,0 +1,133 @@ +--- +title: 'Window: error event' +slug: Web/API/Window/error_event +translation_of: Web/API/Window/error_event +--- +
{{APIRef}}
+ +

当资源加载失败或无法使用时,会在{{domxref("Window")}}对象触发error事件。例如:script 执行时报错。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{domxref("Event")}} or {{domxref("UIEvent")}}
Event handler property(事件处理程序属性)onerror
+ +

如果它是由用户界面元素生成的,或者是由事件实例生成的,那么此事件是{{domxref("UIEvent")}}实例。

+ +

示例

+ +

在线示例

+ +

HTML

+ +
<div class="controls">
+  <button id="script-error" type="button">Generate script error</button>
+  <img class="bad-img" />
+</div>
+
+<div class="event-log">
+  <label>Event log:</label>
+  <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
+</div>
+ + + +

JS

+ +
const log = document.querySelector('.event-log-contents');
+
+window.addEventListener('error', (event) => {
+    log.textContent = log.textContent + `${event.type}: ${event.message}\n`;
+    console.log(event)
+});
+
+const scriptError = document.querySelector('#script-error');
+scriptError.addEventListener('click', () => {
+    const badCode = 'const s;';
+    eval(badCode);
+});
+
+ +

结果

+ +

{{ EmbedLiveSample('Live_example', '100%', '150px') }}

+ +

规范

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('UI Events', '#event-type-error')}}{{Spec2('UI Events')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.error_event")}}

+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/event/index.html b/files/zh-cn/web/api/window/event/index.html new file mode 100644 index 0000000000..a46da74b26 --- /dev/null +++ b/files/zh-cn/web/api/window/event/index.html @@ -0,0 +1,84 @@ +--- +title: Window.event +slug: Web/API/Window/event +tags: + - API + - DOM + - Window + - 事件 + - 方法 +translation_of: Web/API/Window/event +--- +

{{APIRef}}

+ +

{{ Non-standard_header() }}

+ +

window.event 是一个由微软IE引入的属性,只有当DOM事件处理程序被调用的时候会被用到。它的值是当前正在处理的事件对象。

+ +

规范

+ +

没有任何规范。

+ +

微软在MSDN上有相关介绍

+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }} 

+ +
+ + + + + + + + + + + + + + + + + + + + + +
特性ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支持{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatNo() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
特性AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome Mobile
基本支持{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

更多资料

+ + diff --git a/files/zh-cn/web/api/window/external/index.html b/files/zh-cn/web/api/window/external/index.html new file mode 100644 index 0000000000..0453fa1fb0 --- /dev/null +++ b/files/zh-cn/web/api/window/external/index.html @@ -0,0 +1,55 @@ +--- +title: Window.external +slug: Web/API/Window/external +tags: + - API + - Deprecated + - Window + - external +translation_of: Web/API/Window/external +--- +
{{APIRef}} {{deprecated_header}}
+ +

{{domxref("Window")}} API 的 external 属性返回一个 External 接口的实例,这个接口本来用于包含一些用来向浏览器添加外部搜索提供者(external search providers)的函数,但是,现在这个属性已被废弃,其中的函数现在都是空函数,无任何功能,仅为了符合规范而存在。

+ +

方法

+ +

External 对象有以下方法:

+ + + + + + + + + + + + + + + + +
方法描述
AddSearchProvider(descriptionURL)空函数,无任何作用。参见 Autodiscovery of search plugins
IsSearchProviderInstalled()空函数,无任何作用。
+ +

规范

+ + + + + + + + + + + + +
规范状态
{{SpecName('HTML WHATWG', '#external', 'External')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.external")}}

diff --git a/files/zh-cn/web/api/window/find/index.html b/files/zh-cn/web/api/window/find/index.html new file mode 100644 index 0000000000..9574fcf20a --- /dev/null +++ b/files/zh-cn/web/api/window/find/index.html @@ -0,0 +1,47 @@ +--- +title: window.find +slug: Web/API/Window/find +translation_of: Web/API/Window/find +--- +

{{ ApiRef() }}

+

{{ note(" window.find()可能会在未来版本的Gecko中被废弃 .  查看 Bug(672395) .") }}  

+

概述

+

在一个页面中搜索指定的字符串.

+

语法

+
window.find(aString, aCaseSensitive, aBackwards, aWrapAround,
+            aWholeWord, aSearchInFrames, aShowDialog);
+
+
+
+ aString
+
+ 将要搜索的字符串
+
+ aCaseSensitive
+
+ 布尔值,如果为true,表示搜索是区分大小写的.
+
+ aBackwards
+
+ 布尔值.如果为true, 表示搜索方向为向上搜索.
+
+ aWrapAround
+
+ 布尔值.如果为true, 表示为循环搜索.
+
+ aWholeWord {{ unimplemented_inline() }}
+
+ 布尔值.如果为true,表示采用全字匹配搜索.该参数无效; 查看 {{ bug("481513") }}.
+
+ aSearchInFrames
+
+ 布尔值.如果为true, 表示会搜索框架内的文本.
+
+ aShowDialog
+
+ 布尔值.如果为true, 则会弹出一个搜索对话框.
+
+

返回值

+

如果搜索到指定的字符串,则返回true,否则返回false.

+

规范

+

{{ DOM0() }}

diff --git a/files/zh-cn/web/api/window/focus/index.html b/files/zh-cn/web/api/window/focus/index.html new file mode 100644 index 0000000000..984020d0e5 --- /dev/null +++ b/files/zh-cn/web/api/window/focus/index.html @@ -0,0 +1,41 @@ +--- +title: Window.focus() +slug: Web/API/Window/focus +tags: + - API +translation_of: Web/API/Window/focus +--- +

{{APIRef}}

+ +

概述

+ +

请求将窗口显示在前(靠近屏幕),这可能由于用户设置而失败,并且该窗口在方法返回之前不能保证会显示在最前.

+ +

语法

+ +
window.focus()
+
+ +

示例

+ +
if (clicked) { window.focus(); }
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','interaction.html#dom-window-focus','Window.focus()')}}{{Spec2('HTML WHATWG')}} 
+ +

{{ languages( { "ja": "ja/DOM/window.focus", "pl": "pl/DOM/window.focus" } ) }}

diff --git a/files/zh-cn/web/api/window/focus_event/index.html b/files/zh-cn/web/api/window/focus_event/index.html new file mode 100644 index 0000000000..a5450ca2ec --- /dev/null +++ b/files/zh-cn/web/api/window/focus_event/index.html @@ -0,0 +1,120 @@ +--- +title: 'Window: focus event' +slug: Web/API/Window/focus_event +tags: + - API + - Event + - Focus +translation_of: Web/API/Window/focus_event +--- +
{{APIRef}}
+ +

当元素获得焦点时, focus 事件就会触发。

+ +

与 focus 相反的事件是 {{domxref("Window/blur_event", "blur")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bubbles(支持冒泡)No
Cancelable(可撤销)No
Interface(接口){{DOMxRef("FocusEvent")}}
Event handler property(事件处理程序属性){{domxref("GlobalEventHandlers/onfocus", "onfocus")}}
Sync / Async(同步/异步)Sync
Composed(可组成)Yes
+ +

示例

+ +

在线示例

+ +

本示例在失去焦点时更改文档的外观。它使用 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 监听 focus 和 {{domxref("Window/blur_event", "blur")}} 事件。

+ +

HTML

+ +
<p id="log">Click on this document to give it focus.</p>
+ +

CSS

+ +
.paused {
+  background: #ddd;
+  color: #555;
+}
+ +

JavaScript

+ +
function pause() {
+  document.body.classList.add('paused');
+  log.textContent = 'FOCUS LOST!';
+}
+
+function play() {
+  document.body.classList.remove('paused');
+  log.textContent = 'This document has focus. Click outside the document to lose focus.';
+}
+
+const log = document.getElementById('log');
+
+window.addEventListener('blur', pause);
+window.addEventListener('focus', play);
+ +

结果

+ +

{{EmbedLiveSample("Live_example")}}

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("UI Events", "#event-type-focus")}}{{Spec2("UI Events")}}添加了组成此事件的信息。
{{SpecName("DOM3 Events", "#event-type-focus")}}{{Spec2("DOM3 Events")}}初始定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.focus_event")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/frameelement/index.html b/files/zh-cn/web/api/window/frameelement/index.html new file mode 100644 index 0000000000..12c587d725 --- /dev/null +++ b/files/zh-cn/web/api/window/frameelement/index.html @@ -0,0 +1,73 @@ +--- +title: window.frameElement +slug: Web/API/Window/frameElement +translation_of: Web/API/Window/frameElement +--- +

{{ ApiRef() }}

+

概述

+

返回嵌入当前window对象的元素(比如 <iframe> 或者 <object>),如果当前window对象已经是顶层窗口,则返回null.

+

语法

+
var frameEl = window.frameElement;
+
+

例子

+
var frameEl = window.frameElement;
+// 如果当前窗口被包含在一个框架里面,则将该框架的地址跳到'http://mozilla.org/'
+if (frameEl)
+  frameEl.src = 'http://mozilla.org/';
+
+

备注

+

虽然该属性名为frameElement,但该属性也会返回其他类型比如 <object> 或者其他可嵌入窗口的元素.

+

相关链接

+ +

规范

+

WHATWG

+

浏览器兼容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support18{{ CompatGeckoDesktop("1") }}5.5?{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoDesktop("1") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

{{ languages( { "ja": "ja/DOM/window.frameElement", "pl": "pl/DOM/window.frameElement", "en": "en/DOM/window.frameElement" } ) }}

diff --git a/files/zh-cn/web/api/window/frames/index.html b/files/zh-cn/web/api/window/frames/index.html new file mode 100644 index 0000000000..2d3331b096 --- /dev/null +++ b/files/zh-cn/web/api/window/frames/index.html @@ -0,0 +1,56 @@ +--- +title: Window.frames +slug: Web/API/Window/frames +translation_of: Web/API/Window/frames +--- +

{{ApiRef("Window")}}

+ +

概要

+ +

返回当前窗口,一个类数组对象,列出了当前窗口的所有直接子窗口。

+ +

语法

+ +
frameList = window.frames;
+
+ + + +

实例

+ +
var frames = window.frames; // 或 // var frames = window.parent.frames;
+for (var i = 0; i < frames.length; i++) {
+  // 在这对frames的一个frame做点什么
+  frames[i].document.body.style.background = "red";
+
+}
+
+ +

规范

+ +

{{ DOM0() }}

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-frames','Window.frames')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-frames', 'Window.frames')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/zh-cn/web/api/window/fullscreen/index.html b/files/zh-cn/web/api/window/fullscreen/index.html new file mode 100644 index 0000000000..3460bad775 --- /dev/null +++ b/files/zh-cn/web/api/window/fullscreen/index.html @@ -0,0 +1,48 @@ +--- +title: Window.fullScreen +slug: Web/API/Window/fullScreen +translation_of: Web/API/Window/fullScreen +--- +
{{APIRef}}
+ +

概述

+ +

这个属性表明了窗口是否处于全屏模式下。仅在Gecko 1.9(Firefox 3)以及之后的版本中有意义,详情参见后附备注。

+ +

语法

+ +
isInFullScreen = windowRef.fullScreen;
+
+ +

在取得chrome privileges的情况下,这个属性是可读写的,否则将是只读属性。如果你试图在未取得chrome privileges的情况下设置这个属性,虽然实际上修改会失败,却并不会抛出错误。这是为了阻止在IE浏览器中意图通过修改这个属性而进行恶意攻击的脚本。

+ +

返回值

+ +
+
isInFullScreen
+
一个布尔值. 可能的值如下:
+
+ + + +

示例

+ +
if (window.fullScreen) {
+    // it's fullscreen!
+} else {
+    // not fullscreen!
+}
+ +

规范

+ +

DOM 0 级。 window.fullScreen 并不属于任何 W3C 规范或技术推荐中。

+ +

备注

+ + diff --git a/files/zh-cn/web/api/window/gamepadconnected_event/index.html b/files/zh-cn/web/api/window/gamepadconnected_event/index.html new file mode 100644 index 0000000000..e1198abe75 --- /dev/null +++ b/files/zh-cn/web/api/window/gamepadconnected_event/index.html @@ -0,0 +1,90 @@ +--- +title: gamepadconnected +slug: Web/API/Window/gamepadconnected_event +tags: + - Gamepad + - gamepadconnected +translation_of: Web/API/Window/gamepadconnected_event +--- +

gamepadconnected 事件会在浏览器检测到游戏控制器第一次连接或者第一次按下游戏键/摇杆的时候触发。

+ +

基本信息

+ +
+
文档
+
Gamepad
+
类型
+
事件
+
冒泡
+
No
+
可取消
+
No
+
Target
+
DefaultView (<window>)
+
默认操着
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target 只读{{domxref("DOMString")}}事件目标(DOM树中的顶层,即document.documentElement)。
type 只读 +

{{domxref("EventTarget")}}

+
事件的类型。
bubbles 只读{{jsxref("Boolean")}}事件是否正常冒泡。
cancelable 只读{{jsxref("Boolean")}}事件是否可以取消。
gamepad 只读{{domxref("Gamepad")}}单个游戏手柄属性,可用于访问关联游戏手柄的数据。
+ +

示例

+ +
// 请注意,在实现该API的浏览器中,该API仍为供应商前缀
+window.addEventListener("gamepadconnected", function( event ) {
+
+    // 所有按钮和轴值均可通过以下方式访问
+    event.gamepad;
+
+});
+
+ +

相关事件

+ + + +

还可以参考

+ + diff --git a/files/zh-cn/web/api/window/getattention/index.html b/files/zh-cn/web/api/window/getattention/index.html new file mode 100644 index 0000000000..f17531eb18 --- /dev/null +++ b/files/zh-cn/web/api/window/getattention/index.html @@ -0,0 +1,33 @@ +--- +title: Window.getAttention() +slug: Web/API/Window/getAttention +translation_of: Web/API/Window/getAttention +--- +
{{ ApiRef() }}
+ +

The Window.getAttention() method attempts to get the user's attention. The mechanism for this happening depends on the specific operating system and window manager.

+ +

语法

+ +
window.getAttention();
+
+ +

Notes

+ +

On Windows, the taskbar button for the window flashes, if this hasn't been disabled by the user.

+ +

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.

+ +

On Macintosh, the icon in the upper right corner of the desktop flashes.

+ +

The function is disabled for web content. Neither Gecko nor Internet Explorer supports this feature now for web content. getAttention will still work when used from chrome in a Gecko application.

+ +

Specification

+ +

DOM Level 0. Not part of specification.

+ +

Browser compatibility

+ + + +

{{Compat("api.Window.getAttention")}}

diff --git a/files/zh-cn/web/api/window/getcomputedstyle/index.html b/files/zh-cn/web/api/window/getcomputedstyle/index.html new file mode 100644 index 0000000000..34d2cb20eb --- /dev/null +++ b/files/zh-cn/web/api/window/getcomputedstyle/index.html @@ -0,0 +1,151 @@ +--- +title: Window.getComputedStyle() +slug: Web/API/Window/getComputedStyle +tags: + - API + - CSSOM View + - setProperty +translation_of: Web/API/Window/getComputedStyle +--- +
{{APIRef}}
+ +

摘要

+ +

Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值。 私有的CSS属性值可以通过对象提供的API或通过简单地使用CSS属性名称进行索引来访问。

+ +

语法

+ +
let style = window.getComputedStyle(element, [pseudoElt]);
+
+ +
+
element
+
 用于获取计算样式的{{domxref("Element")}}。
+
pseudoElt {{optional_inline}}
+
指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)。
+
+ +
注意:在Gecko2.0 {{geckoRelease("2.0")}}之前版本,参数pseudoElt是必要的。如果为null,则不指定其他主要浏览器必须指定此参数。Gecko已经更改为匹配其他浏览器的行为。
+ +

返回的style是一个实时的 {{domxref("CSSStyleDeclaration")}} 对象,当元素的样式更改时,它会自动更新本身。

+ +

示例

+ +
let elem1 = document.getElementById("elemId");
+let style = window.getComputedStyle(elem1, null);
+
+// 它等价于
+// let style = document.defaultView.getComputedStyle(elem1, null);
+
+ +
<style>
+ #elem-container{
+   position: absolute;
+   left:     100px;
+   top:      200px;
+   height:   100px;
+ }
+</style>
+
+<div id="elem-container">dummy</div>
+<div id="output"></div>
+
+<script>
+  function getTheStyle(){
+    let elem = document.getElementById("elem-container");
+    let theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
+    document.getElementById("output").innerHTML = theCSSprop;
+   }
+  getTheStyle();
+</script>
+
+ +
function dumpComputedStyles(elem,prop) {
+
+  let cs = window.getComputedStyle(elem,null);
+  if (prop) {
+    dump("    "+prop+" : "+cs.getPropertyValue(prop)+"\n");
+    return;
+  }
+  let len = cs.length;
+  for (var i=0;i<len;i++) {
+
+    let style = cs[i];
+    dump("    "+style+" : "+cs.getPropertyValue(style)+"\n");
+  }
+
+}
+
+
+ +

描述

+ +

返回的对象与从元素的 {{domxref("HTMLElement.style", "style")}}  属性返回的对象具有相同的类型;然而,两个对象具有不同的目的。从getComputedStyle返回的对象是只读的,可以用于检查元素的样式(包括由一个<style>元素或一个外部样式表设置的那些样式)。elt.style对象应用于在特定元素上设置样式。

+ +

第一个参数必须是Element对象(传递一个非节点元素,如 一个#text 节点, 将会抛出一个错误). 从Gecko 1.9.2   {{geckoRelease("1.9.2")}} 开始, 现在返回的一个在URL周围有引号的URL值,像这样: url("http://foo.com/bar.jpg").

+ +

defaultView

+ +

在许多在线的演示代码中,getComputedStyle是通过 document.defaultView 对象来调用的。大部分情况下,这是不需要的,因为可以直接通过window对象调用。但有一种情况,你必需要使用 defaultView,  那是在firefox3.6上访问子框架内的样式 。

+ +

与伪元素一起使用

+ +

getComputedStyle 可以从伪元素拉取样式信息 (比如, ::after, ::before, ::marker, ::line-marker—查看 详情 这里).

+ +
<style>
+    h3::after {
+        content: "rocks!";
+    }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+    let h3 = document.querySelector('h3'),
+    result = getComputedStyle(h3, '::after').content;
+    alert(`the generated content is: ${result}`);
+    console.log(`the generated content is: ${result}`);
+    // the generated content is: "rocks!"
+</script>
+
+
+ +

注意

+ +

 

+ +

返回的{{domxref("CSSStyleDeclaration")}}对象将包含所有受支持的CSS属性长名称的活动值。示例名称是border-bottom-widthborder-widthborder是示例速记属性名称。仅使用像font-size这样的名字来查询值是最安全的。 查询诸如font等简写名称不适用于大多数浏览器。

+ +

CSS规范也允许使用驼峰命名,比如fontSizepaddingTop

+ +

CSS属性值可以使用getPropertyValue(propName)API或直接索引到对象,如cs ['z-index']cs.zIndex

+ +

 

+ +

getComputedStyle的返回值是 {{cssxref("resolved_value", "resolved values")}},  通常跟CSS2.1中的{{cssxref("computed_value","computed values")}}是相同的值。 但对于一些旧的属性,比如width, height, padding 它们的值又为 {{cssxref("used_value","used values")}}。 最初, CSS2.0定义的计算值Computed values 就是属性的最终值。 但是CSS2.1 重新定义了 computed values 为布局前的值, used values布局后的值。 布局前与布局后的区别是, width 或者 height的 百分比可以代表元素的宽度,在布局后会被像素值替换.

+ +

在某些情况下,通过浏览器会特意返回不准确的值。 特别是在避免CSS 浏览历史泄露的安全问题, 比如,浏览者看过某个网站, 它的链接通常会变成蓝色带下划线的链接,通过判断链接的颜色(getComputedSytle(node, null).color) 是否为蓝色,就会泄露用户的浏览历史, 所以浏览器会特意返回不准确的值,保护用户隐私。可以了解更多关于css安全的链接http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/

+ +

在CSS过渡期间,getComputedStyle返回Firefox中的原始属性值,但返回WebKit中的最终属性值。

+ +

在Firefox中,属性值为auto的会直接返回使用值,而不是auto。比如,你在设定了一个元素的css为height:30px; top: auto; bottom:0;它的父元素height:100px;,在请求top的计算样式时,Firefox会返回'70px' = 100px - 30px;

+ +

浏览器兼容

+ + + +

{{Compat("api.Window.getComputedStyle")}}

+ +

规范

+ + + +

参见

+ + diff --git a/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html new file mode 100644 index 0000000000..2ec99a1b9a --- /dev/null +++ b/files/zh-cn/web/api/window/getdefaultcomputedstyle/index.html @@ -0,0 +1,144 @@ +--- +title: Window.getDefaultComputedStyle() +slug: Web/API/Window/getDefaultComputedStyle +translation_of: Web/API/window/getDefaultComputedStyle +--- +
{{APIRef("CSSOM")}}{{Non-standard_header}}
+ +

getDefaultComputedStyle() 给出元素的所有CSS属性的默认计算值(computed values ),忽略作者样式。也就是说,只考虑用户代理和用户风格。

+ +

语法及参数说明

+ +
let style = window.getDefaultComputedStyle(element[, pseudoElt]);
+
+ +
+
element
+
获取计算样式的元素
+
pseudoElt {{optional_inline}}
+
指定匹配的伪类. 通常情况下可以为空.
+
+ +

返回的样式是一个 CSSStyleDeclaration 对象.

+ +

例子

+ +
var elem1 = document.getElementById("elemId");
+var style = window.getDefaultComputedStyle(elem1);
+
+ +
<style>
+#elem-container {
+   position: absolute;
+   left:     100px;
+   top:      200px;
+   height:   100px;
+ }
+</style>
+
+<div id="elem-container">dummy</div>
+<div id="output"></div>
+
+<script>
+    var elem = document.getElementById("elem-container");
+    var theCSSprop = window.getDefaultComputedStyle(elem).position;
+    document.getElementById("output").innerHTML = theCSSprop; // 将会输出 "static"
+</script>   
+ +

Description

+ +

The returned object is of the same type as the object returned by getComputedStyle, but only takes into account user-agent and user rules.

+ +

使用伪元素

+ +

getDefaultComputedStyle 同样可以从伪元素中获取属性 (比如, ::after, ::before).

+ +
<style>
+ h3:after {
+   content: ' rocks!';
+ }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+  var h3       = document.querySelector('h3'),
+      result   = getDefaultComputedStyle(h3, ':after').content;
+
+  console.log('the generated content is: ', result); // 返回 'none'
+</script>
+
+ +

备注

+ +

The returned value is, in certain known cases, expressly incorrect by deliberate intent. In particular, to avoid the so called CSS History Leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site, and/or limit the styles that can be applied using the :visited pseudo-selector. See http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/ and http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/ for details of the examples of how this is implemented.

+ +

Specifications

+ +

Proposed to the CSS working group.

+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
pseudo-element support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}197.5{{CompatNo}}{{CompatNo}}
pseudo-element support{{CompatNo}}19{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/window/getselection/index.html b/files/zh-cn/web/api/window/getselection/index.html new file mode 100644 index 0000000000..6c2bebc684 --- /dev/null +++ b/files/zh-cn/web/api/window/getselection/index.html @@ -0,0 +1,82 @@ +--- +title: Window.getSelection +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +
+ +

返回一个 {{domxref("Selection")}} 对象,表示用户选择的文本范围或光标的当前位置。

+ +

语法

+ +
const selection = window.getSelection() ;
+ + + +

示例

+ +
function foo() {
+    let selObj = window.getSelection();
+    console.log(selObj);
+    let selRange = selObj.getRangeAt(0);
+    // 其他代码
+}
+ +

备注

+ +

在  JavaScript中,当一个对象被传递给期望字符串作为参数的函数中时(如 {{ Domxref("window.alert") }} 或 {{ Domxref("document.write") }}),对象的{{jsxref("Object.toString","toString()")}}方法会被调用,然后将返回值传给该函数。

+ +

在上例中,selObj.toString() 会在传递到 {{domxref("window.alert()")}}时自动调用。然而,当你试图在 {{domxref("Selection")}} 对象上使用一个 JavaScript 的{{jsxref("Global_Objects/String", "String")}} 对象上的属性或者方法时(如 {{jsxref("String.prototype.length")}} 或者 {{jsxref("String.prototype.substr()")}}),会导致错误(如果没有相应的属性或方法时)或返回不是期望的结果(如果存在相应的属性或方法)。如果想要将 Selection 对象作为一个字符串使用,请直接调用 toString() 方法:

+ +
var selectedText = selObj.toString();
+ + + +

相关对象

+ + + +

你还可以使用 {{domxref("Document.getSelection()")}},两个方法等价。

+ +

值得注意的是,目前在Firefox, Edge (非 Chromium 版本) 及 Internet Explorer 中,getSelection() 对 {{htmlelement("textarea")}} 及 {{htmlelement("input")}} 元素不起作用。 {{domxref("HTMLInputElement.setSelectionRange()")}} 或 selectionStart 及 selectionEnd 属性可用于解决此问题。

+ +

还要注意选择不同于焦点(详见 Selection 及输入焦点)。可使用{{domxref("Document.activeElement")}} 来返回当前的焦点元素.

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.getSelection")}}

+ +

相关链接

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
diff --git a/files/zh-cn/web/api/window/hashchange_event/index.html b/files/zh-cn/web/api/window/hashchange_event/index.html new file mode 100644 index 0000000000..de51f52ff8 --- /dev/null +++ b/files/zh-cn/web/api/window/hashchange_event/index.html @@ -0,0 +1,88 @@ +--- +title: 'Window: hashchange event' +slug: Web/API/Window/hashchange_event +tags: + - API + - DOM + - Event + - HashChange + - Window + - onhashchange + - 事件 + - 参考 +translation_of: Web/API/Window/hashchange_event +--- +

{{APIRef}}

+ +

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

+ + + + + + + + + + + + + + + + + + + + +
BubblesYes
CancelableNo
Interface{{domxref("HashChangeEvent")}}
Event handler{{domxref("WindowEventHandlers/onhashchange", "onhashchange")}}
+ +

示例

+ +

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

+ +
window.addEventListener('hashchange', function() {
+  console.log('The hash has changed!')
+}, false);
+ +

或使用 onhashchange 事件处理程序属性:

+ +
function locationHashChanged() {
+  if (location.hash === '#cool-feature') {
+    console.log("You're visiting a cool feature!");
+  }
+}
+
+window.onhashchange = locationHashChanged;
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('HTML WHATWG', 'indices.html#event-hashchange', 'hashchange')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.hashchange_event")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/history/index.html b/files/zh-cn/web/api/window/history/index.html new file mode 100644 index 0000000000..118bfe284c --- /dev/null +++ b/files/zh-cn/web/api/window/history/index.html @@ -0,0 +1,34 @@ +--- +title: Window.history +slug: Web/API/Window/history +translation_of: Web/API/Window/history +--- +

{{ ApiRef("Window") }}

+ +

Window.history是一个只读属性,用来获取{{domxref("History")}} 对象的引用,{{domxref("History")}} 对象提供了操作浏览器会话历史(浏览器地址栏中访问的页面,以及当前页面中通过框架加载的页面)的接口。

+ +

History对象有如下方法:参见 Manipulating the browser history 中的示例和详情。尤其指出的是文章里解释了在使用pushState()replaceState()方法前,你需要了解的安全问题。

+ +

语法

+ +
var historyObj = window.history;
+ +

示例

+ +
history.back();     // 等同于点击浏览器的回退按钮
+history.go(-1);     //等同于history.back();
+
+ +

附注

+ +

在顶层页面中,浏览器的回退和前进按钮旁的下拉菜单显示了可以通过History对象访问到的页面会话历史(session history)列表。

+ +

出于安全考虑,History对象不允许未授权代码访问会话历史(session History)中其它页面的URLs,但可以导航到其它会话历史(session History)指向的页面。

+ +

未授权代码无法清除会话历史(session History),也不能禁用回退/前进功能。最快捷的可用方式是使用location.replace()方法,提供指定的URL来替换当前的会话历史(session history)。

+ +

规范

+ + diff --git a/files/zh-cn/web/api/window/index.html b/files/zh-cn/web/api/window/index.html new file mode 100644 index 0000000000..8024186e44 --- /dev/null +++ b/files/zh-cn/web/api/window/index.html @@ -0,0 +1,727 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - JavaScript + - Window + - global + - 作用域 + - 全局 + - 参考 + - 接口 + - 标签页 + - 浏览器 +translation_of: Web/API/Window +--- +
{{APIRef("DOM")}}
+ +

window 对象表示一个包含DOM文档的窗口, document 属性指向窗口中载入的 DOM文档 。使用 {{ Domxref("document.defaultView") }} 属性可以获取指定文档所在窗口。

+ +

window作为全局变量,代表了脚本正在运行的窗口,暴露给 Javascript 代码。

+ +

本节为 DOM Window 对象中可用的所有方法、属性和事件提供简要参考。window 对象实现了 Window 接口,此接口继承自 AbstractView 接口。一些额外的全局函数、命名空间、对象、接口和构造函数与 window 没有典型的关联,但却是有效的,它们在 JavaScript参考DOM参考 中列出。

+ +

在有标签页功能的浏览器中,每个标签都拥有自己的 window 对象;也就是说,同一个窗口的标签页之间不会共享一个 window 对象。有一些方法,如 {{ Domxref("window.resizeTo") }} 和 {{ Domxref("window.resizeBy") }} 之类的方法会作用于整个窗口而不是 window 对象所属的那个标签。一般而言,如果一样东西无法恰当地作用于标签,那么它就会作用于窗口。

+ +

{{InheritanceDiagram}}

+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

属性

+ +

这个接口从 {{domxref("EventTarget")}} 接口继承属性,也从 {{domxref("WindowOrWorkerGlobalScope")}} 和 {{domxref("WindowEventHandlers")}} 这两个 mixin 中继承属性。

+ +

注意,对象类型的属性(例如:覆盖内建元素的原型)被列于下面单独的小节之中。

+ +
+
{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}
+
这个属性指示当前窗口是否关闭。
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
返回 console 对象的引用,该对象提供了对浏览器调试控制台的访问。
+
{{domxref("Window.content")}} 和 Window._content {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}
+
返回当前 window 的 content 元素的引用。通过带下划线的过时变种方法不再可以获得 Web content。
+
{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
返回当前 chrome window 的 XUL 控制器对象。
+
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
+
returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new custom elements and get information about previously registered custom elements.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
返回浏览器 crypto 对象。
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
获取或设置指定窗口的状态栏文本。
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
返回当前显示器的物理像素和设备独立像素的比例。
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
获取在调用 {{domxref("window.showModalDialog()")}} 时传递给窗口的参数(如果它是一个对话框)。这是一个 {{Interface("nsIArray")}}。
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
{{domxref("window.personalbar")}} 的另一种形式。
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
返回对当前窗口所包含文档的引用。
+
{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.
+
{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.
+
{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.
+
{{domxref("Window.event")}} {{ReadOnlyInline}}
+
Returns the current event, which is the event currently being handled by the JavaScript code's context, or undefined if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
返回嵌入窗口的元素,如果未嵌入窗口,则返回null。
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
返回当前窗口中所有子窗体的数组。
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
此属性表示窗口是否以全屏显示。
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Gecko 13 (Firefox 13) 开始废弃。使用 {{domxref("Window.localStorage")}} 替代它。
+ 原本是:用于存储跨页面数据的多重存储对象。
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
返回一个对 history 对象的引用。
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
获得浏览器窗口的内容区域的高度,包含水平滚动条(如果有的话)。
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
获得浏览器窗口的内容区域的宽度,包含垂直滚动条(如果有的话)。
+
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
+
指出上下文环境是否能够使用安全上下文环境的特征。
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
返回窗口中的 frames 数量。参见 {{domxref("window.frames")}}。
+
{{domxref("Window.location")}}
+
获取、设置 window 对象的 location, 或者当前的 URL.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
返回 locationbar 对象,其可视性可以在窗口中切换。
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
返回用来存储只能在创建它的源下访问的数据的本地存储对象的引用
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
返回菜单条对象,它的可视性可以在窗口中切换
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
返回窗口的 message manager 对象。
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
返回当前动画循环开始经过的毫秒数
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
获取/设置窗口的名称。
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
返回对 navigator 对象的引用。
+
{{domxref("Window.opener")}}
+
返回对打开当前窗口的那个窗口的引用。
+
{{domxref("Window.orientation")}} {{non-standard_inline}} {{deprecated_inline}} {{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
返回浏览器窗口的外部高度。
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
返回浏览器窗口的外部宽度。
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
{{domxref("window.scrollX")}}的别名。
+
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
+
{{domxref("window.scrollY")}}的别名。
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
返回当前窗口或子窗口的父窗口的引用。
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
返回 personalbar 对象,它的可视性可以在窗口中切换。
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+
{{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{readOnlyInline}}
+
Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.
+
{{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{readOnlyInline}}
+
Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

方法

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

+ +
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves back one in the window history. This method is obsolete; you should instead use {{domxref("History.back", "window.history.back()")}}.
+
{{domxref("Window.blur()")}}
+
Sets focus away from the window.
+
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
+
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
+
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
+
Registers the window to capture all events of the specified type.
+
{{domxref("Window.clearImmediate()")}}
+
Cancels the repeated execution set using setImmediate.
+
{{domxref("Window.close()")}}
+
Closes the current window.
+
{{domxref("Window.confirm()")}}
+
Displays a dialog with a message that the user needs to respond to.
+
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves the window one document forward in the history. This method is obsolete; you should instead use {{domxref("History.forward", "window.history.forward()")}}.
+
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Flashes the application icon.
+
{{domxref("Window.getAttentionWithCycleCount()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.getComputedStyle()")}}
+
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
+
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
+
Gets default computed style for the specified element, ignoring author stylesheets.
+
{{domxref("Window.getSelection()")}}
+
Returns the selection object representing the selected item(s).
+
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Returns the browser to the home page.
+
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
打开一个新窗口。
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
打开一个新的对话框窗口。
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
为一个窗口向另一个窗口发送数据字符串提供了一种安全方法,该窗口不必与第一个窗口处于相同的域中。
+
{{domxref("Window.print()")}}
+
打开打印对话框以打印当前文档。
+
{{domxref("Window.prompt()")}}
+
返回用户在提示对话框中输入的文本。
+
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
释放捕获特定类型事件的窗口。
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
告诉浏览器一个动画正在进行中,请求浏览器为下一个动画帧重新绘制窗口。
+
{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}
+
启用在浏览器空闲期间对任务进行调度。
+
{{domxref("Window.resizeBy()")}}
+
将当前窗口调整到一定的大小。
+
{{domxref("Window.resizeTo()")}}
+
动态调整窗口。
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
滚动窗口到文档中的特定位置。
+
{{domxref("Window.scrollBy()")}}
+
按给定的数量在窗口中滚动文档。
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
按给定行数滚动文档。
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
按指定页数滚动当前文档。
+
{{domxref("Window.scrollTo()")}}
+
滚动到文档中的特定坐标集。
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
更改当前窗口的光标。
+
{{domxref("Window.setImmediate()")}}
+
在浏览器完成其他繁重任务后执行一个函数。
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
切换用户调整窗口大小的能力。
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
根据内容设置窗口大小。
+
{{domxref("Window.stop()")}}
+
这个方法停止窗口加载。
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
更新当前chrome窗口(UI)命令的状态。
+
+ +

Methods implemented from elsewhere

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
Starts the process of fetching a resource from the network.
+
{{domxref("EventTarget.removeEventListener")}}
+
Removes an event listener from the window.
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

Obsolete methods

+ +
+
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
+
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
+
+ +

Event handlers

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

+ +
+

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

+
+ +
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Event handlers implemented from elsewhere

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back button is pressed.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
+ +

Events

+ +

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

+ +
+
error
+
Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
+ Also available via the {{domxref("GlobalEventHandlers/onerror", "onerror")}} 属性。
+
languagechange
+
Fired at the global scope object when the user's preferred language changes.
+ Also available via the onlanguagechange 属性。
+
orientationchange
+
Fired when the orientation of the device has changed.
+ Also available via the onorientationchange 属性。
+
devicemotion
+
Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
+
deviceorientation
+
Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
+
{{domxref("Document/defaultView/resize_event", "resize")}}
+
Fired when the window has been resized.
+ Also available via the onresize 属性。
+
{{domxref("Document/defaultView/storage_event", "storage")}}
+
Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
+ Also available via the onstorage 属性。
+
+ +

Animation events

+ +
+
animationcancel
+
Fired when an animation unexpectedly aborts.
+ Also available via the onanimationcancel 属性。
+
animationend
+
Fired when an animation has completed normally.
+ Also available via the onanimationend 属性。
+
animationiteration
+
Fired when an animation iteration has completed.
+ Also available via the onanimationiteration 属性。
+
animationstart
+
Fired when an animation starts.
+ Also available via the onanimationstart 属性。
+
+ +

Clipboard events

+ +
+
clipboardchange
+
Fired when the system clipboard content changes.
+
copy
+
Fired when the user initiates a copy action through the browser's user interface.
+ Also available via the oncopy 属性。
+
cut
+
Fired when the user initiates a cut action through the browser's user interface.
+ Also available via the oncut 属性。
+
paste
+
Fired when the user initiates a paste action through the browser's user interface.
+ Also available via the onpaste 属性。
+
+ +

Connection events

+ +
+
offline
+
Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false.
+ Also available via the {{domxref("WindowEventHandlers.onoffline", "onoffline")}} 属性。
+
online
+
Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true.
+ Also available via the {{domxref("WindowEventHandlers.ononline", "ononline")}} 属性。
+
+ +

Focus events

+ +
+
blur
+
Fired when an element has lost focus.
+ Also available via the onblur 属性。
+
focus
+
Fired when an element has gained focus.
+ Also available via the onfocus property
+
+ +

Gamepad events

+ +
+
gamepadconnected
+
Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
+ Also available via the ongamepadconnected 属性。
+
gamepaddisconnected
+
Fired when the browser detects that a gamepad has been disconnected.
+ Also available via the ongamepaddisconnected property
+
+ +

History events

+ +
+
hashchange
+
Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
+ Also available via the onhashchange 属性。
+
pagehide
+
Sent when the browser hides the current document while in the process of switching to displaying in its palce a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.
+ Also available through the onpagehide event handler 属性。
+
pageshow
+
Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.
+ Also available using the onpageshow event handler 属性。
+
{{domxref("Document/defaultView/popstate_event", "popstate")}}
+
Fired when the active history entry changes.
+ Also available using the onpopstate event handler 属性。
+
+ +

Load & unload events

+ +
+
beforeunload
+
Fired when the window, the document and its resources are about to be unloaded.
+ Also available via the onbeforeunload 属性。
+
DOMContentLoaded
+
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
+
load
+
Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
+ Also available via the onload 属性。
+
unload
+
Fired when the document or a child resource is being unloaded.
+ Also available via the onunload 属性。
+
+ +

Manifest events

+ +
+
appinstalled
+
Fired when the browser has successfully installed a page as an application.
+ Also available via the onappinstalled 属性。
+
beforeinstallprompt
+
Fired when a user is about to be prompted to install a web application.
+ Also available via the onbeforeinstallprompt 属性。
+
+ +

Messaging events

+ +
+
message
+
Fired when the window receives a message, for example from a call to Window.postMessage() from another browsing context.
+ Also available via the onmessage 属性。
+
messageerror
+
Fired when a Window object receives a message that can't be deserialized.
+ Also available via the onmessageerror 属性。
+
+ + + +
+
afterprint
+
Fired after the associated document has started printing or the print preview has been closed.
+ Also available via the onafterprint 属性。
+
beforeprint
+
Fired when the associated document is about to be printed or previewed for printing.
+ Also available via the onbeforeprint 属性。
+
+ +

Promise rejection events

+ +
+
rejectionhandled
+
Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection.
+ Also available through the onrejectionhandled event handler 属性。
+
unhandledrejection
+
Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection.
+ Also available using the onunhandledrejection event handler 属性。
+
+ +

Transition events

+ +
+
transitioncancel
+
Fired when a CSS transition is canceled.
+ Also available via the ontransitioncancel 属性。
+
transitionend
+
Fired when a CSS transition has completed.
+ Also available via the ontransitionend 属性。
+
transitionrun
+
Fired when a CSS transition is first created.
+ Also available via the ontransitionrun 属性。
+
transitionstart
+
Fired when a CSS transition has actually started.
+ Also available via the ontransitionstart 属性。
+
+ +

WebVR events

+ +
+
vrdisplayactivate
+
Fired when a VR display becomes available to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+ Also available via the onvrdisplayactivate 属性。
+
vrdisplayblur
+
Fired when presentation to a VR display has been paused for some reason by the browser, OS, or VR hardware.
+ Also available via the onvrdisplayblur 属性。
+
vrdisplayconnect
+
Fired when a compatible VR display is connected to the computer.
+ Also available via the onvrdisplayconnect 属性。
+
vrdisplaydeactivate
+
Fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+ Also available via the onvrdisplaydeactivate 属性。
+
vrdisplaydisconnect
+
Fired when a compatible VR display is disconnected from the computer.
+ Also available via the onvrdisplaydisconnect 属性。
+
vrdisplayfocus
+
Fired when presentation to a VR display has resumed after being blurred.
+ Also available via the onvrdisplayfocus 属性。
+
vrdisplaypresentchange
+
fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.
+ Also available via the onvrdisplaypresentchange 属性。
+
vrdisplaypointerrestricted
+
Fired when the VR display's pointer input is restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerrestricted 属性。
+
vrdisplaypointerunrestricted
+
Fired when the VR display's pointer input is no longer restricted to consumption via a pointerlocked element.
+ Also available via the onvrdisplaypointerunrestricted 属性。
+
+ +

接口

+ +

See DOM Reference

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/innerheight/index.html b/files/zh-cn/web/api/window/innerheight/index.html new file mode 100644 index 0000000000..d177fd0cd7 --- /dev/null +++ b/files/zh-cn/web/api/window/innerheight/index.html @@ -0,0 +1,122 @@ +--- +title: Window.innerHeight +slug: Web/API/Window/innerHeight +translation_of: Web/API/Window/innerHeight +--- +
{{APIRef}}
+ +

概述

+ +

浏览器窗口的视口(viewport)高度(以像素为单位);如果有水平滚动条,也包括滚动条高度。

+ +
Note: If you use {{ifmethod("nsIDOMWindowUtils", "setCSSViewport")}} to set the virtual window size for page layout purposes, the value returned by this property corresponds to the viewport height set using that method.
+ +

语法

+ +
var intViewportHeight = window.innerHeight;
+ +

+ +

intViewportHeight 为浏览器窗口的视口的高度。

+ +

window.innerHeight 属性为只读,且没有默认值。

+ +

备注

+ +

任何窗口对象,如 {{domxref("window")}}、frame、frameset 或 secondary window 都支持 innerHeight 属性。

+ +

有一个算法用来获取不包括水平滚动条的视口高度。

+ +

例子

+ +

假设有一个 frameset

+ +
var intFrameHeight = window.innerHeight; // or
+
+var intFrameHeight = self.innerHeight;
+// 返回frameset里面的frame视口的高度
+
+var intFramesetHeight = parent.innerHeight;
+// 返回上一级frameset的视口的高度
+
+var intOuterFramesetHeight = top.innerHeight;
+// 返回最外部frameset的视口的高度
+
+ +

{{todo("link to an interactive demo here")}}

+ +

改变一个窗口的大小,可以查看 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+ +

想获取窗口的外层高度(outer height),即整个浏览器窗口的高度,请查看 {{domxref("window.outerHeight")}}。

+ +

图像示例

+ +

下面的示意图展示了 outerHeight 和 innerHeight 两者的区别。

+ +

innerHeight vs outerHeight illustration

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+ +

Gecko 备注

+ +

从 Firefox 4 到 Firefox 24,该属性有 bug,而且某种情况下,会在页面加载前给出一个错误的值,查看 {{bug(641188)}}。

+ +

标准相关信息

+ +

DOM Level 0。不属于任何 W3C 技术规范或推荐。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/innerwidth/index.html b/files/zh-cn/web/api/window/innerwidth/index.html new file mode 100644 index 0000000000..fad1ee4c70 --- /dev/null +++ b/files/zh-cn/web/api/window/innerwidth/index.html @@ -0,0 +1,78 @@ +--- +title: Window.innerWidth +slug: Web/API/Window/innerWidth +tags: + - API + - CSSOM View + - HTML DOM + - innerWidth +translation_of: Web/API/Window/innerWidth +--- +
{{APIRef}}
+ +

只读的 {{domxref("Window")}} 属性 innerWidth 返回以像素为单位的窗口的内部宽度。如果垂直滚动条存在,则这个属性将包括它的宽度。

+ +

更确切地说,innerWidth 返回窗口的 {{Glossary("layout viewport")}} 的宽度。 窗口的内部高度——布局视口的高度——可以从 {{domxref("Window.innerHeight", "innerHeight")}} 属性中获取到。

+ +

语法

+ +
let intViewportWidth = window.innerWidth;
+ +

+ +

一个整数型的值表示窗口的布局视口宽度是以像素为单位的。这个属性是只读的,并且没有默认值。

+ +

若要更改窗口的宽度,请使用 {{domxref("Window")}} 的方法来调整窗口的大小,例如{{domxref("Window.resizeBy", "resizeBy()")}} 或者 {{domxref("Window.resizeTo", "resizeTo()")}}。

+ +

使用说明

+ +

如果你需要获取除去滚动条和边框的窗口宽度,请使用根元素 {{HTMLElement("html")}}  的{{domxref("Element.clientWidth", "clientWidth")}} 属性。

+ +

innerWidth 属性在任何表现类似于窗口的任何窗口或对象(例如框架或选项卡)上都是可用的。

+ +

示例

+ +
// 返回视口的宽度
+var intFrameWidth = window.innerWidth;
+
+// 返回一个框架集内的框架的视口宽度
+var intFrameWidth = self.innerWidth;
+
+// 返回最近的父级框架集的视口宽度
+var intFramesetWidth = parent.innerWidth;
+
+// 返回最外层框架集的视口宽度
+var intOuterFramesetWidth = top.innerWidth;
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('CSSOM View', '#dom-window-innerwidth', 'window.innerWidth')}}{{Spec2('CSSOM View')}}初识定义
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.innerWidth")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/issecurecontext/index.html b/files/zh-cn/web/api/window/issecurecontext/index.html new file mode 100644 index 0000000000..63f29098c9 --- /dev/null +++ b/files/zh-cn/web/api/window/issecurecontext/index.html @@ -0,0 +1,120 @@ +--- +title: Window.isSecureContext +slug: Web/API/Window/isSecureContext +translation_of: Web/API/Window/isSecureContext +--- +

{{APIRef}}{{SeeCompatTable}}

+ +

window.isSecureContext是一个判断上下文是否能够使用安全上下文的特征的只读属性

+ +

语法

+ +
var isSecure = window.isSecureContext
+ +

示例

+ +

特征检测

+ +

你可以使用特征检测来判断上下文是否处于安全的上下文之中通过使用在全局作用域下公共的isSecureContext返回的布尔值。

+ +
if (window.isSecureContext) {
+  // 页面是是个安全的上下文,服务可以正常使用。
+  navigator.serviceWorker.register("/offline-worker.js").then(function () {
+    ...
+  });
+}
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Secure Contexts')}}{{Spec2('Secure Contexts','#monkey-patching-global-object','isSecureContext')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Considers window.opener{{CompatNo}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Considers window.opener{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/languagechange_event/index.html b/files/zh-cn/web/api/window/languagechange_event/index.html new file mode 100644 index 0000000000..953a16707d --- /dev/null +++ b/files/zh-cn/web/api/window/languagechange_event/index.html @@ -0,0 +1,123 @@ +--- +title: languagechange +slug: Web/API/Window/languagechange_event +translation_of: Web/API/Window/languagechange_event +--- +

{{SeeCompatTable}}

+ +

当用户首选语言更改时,将在全局范围对象上触发languagechange事件。

+ +

General info

+ +
+
Specification
+
{{ SpecName('HTML WHATWG', 'indices.html#event-languagechange') }}
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
The default window scope, being {{domxref("Window")}} on Web pages and {{domxref("WorkerGlobalScope")}} in Web Workers.
+
Default Action
+
None
+
+ +

Properties

+ +

Being of type {{domxref("Event")}}, this event implements the properties of this interface.

+ +
+
{{domxref("Event.target")}} {{ReadonlyInline}}
+
Returns an {{domxref("EventTarget")}} that is the topmost target in the DOM tree of the event.
+
{{domxref("Event.type")}} {{ReadonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the type of event, here "languagechange".
+
{{domxref("Event.bubbles")}}{{ReadonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating if the event normally bubbles or not.
+
{{domxref("Event.cancelable")}}{{ReadonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating if it is possible to cancel the event.
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'indices.html#event-languagechange', 'languagechange') }}{{ Spec2('HTML WHATWG') }}Initial definition
{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}{{ Spec2('HTML5.1') }}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support37{{ CompatGeckoDesktop("32") }} [1]{{ CompatNo() }}24{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatGeckoMobile("32") }}[1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

[1]In Firefox, the navigator.languages property's value is taken from the intl.accept_languages preference.

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/length/index.html b/files/zh-cn/web/api/window/length/index.html new file mode 100644 index 0000000000..b5e37e034a --- /dev/null +++ b/files/zh-cn/web/api/window/length/index.html @@ -0,0 +1,21 @@ +--- +title: window.length +slug: Web/API/Window/length +translation_of: Web/API/Window/length +--- +
+ {{ApiRef}}
+

概述

+

返回当前窗口中包含的框架数量(框架包括frameiframe两种元素).

+

语法

+
framesCount = window.length;
+
+ +

示例

+
if (window.length) {
+  // 该窗口包含至少一个子框架
+}
+

规范

+

{{DOM0}}

diff --git a/files/zh-cn/web/api/window/localstorage/index.html b/files/zh-cn/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..0145b13bc7 --- /dev/null +++ b/files/zh-cn/web/api/window/localstorage/index.html @@ -0,0 +1,93 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +tags: + - API + - Storage + - Window + - localStorage + - 只读属性 +translation_of: Web/API/Window/localStorage +--- +

{{APIRef()}}

+ +

只读的localStorage 属性允许你访问一个{{domxref("Document")}} 源(origin)的对象 {{domxref("Storage")}};存储的数据将保存在浏览器会话中localStorage 类似 {{DOMxRef("Window.sessionStorage", "sessionStorage")}},但其区别在于:存储在 localStorage 的数据可以长期保留;而当页面会话结束——也就是说,当页面被关闭时,存储在 sessionStorage 的数据会被清除 。

+ +

应注意,无论数据存储在 localStorage 还是 sessionStorage它们都特定于页面的协议。

+ +

另外,localStorage 中的键值对总是以字符串的形式存储。 (需要注意, 和js对象相比, 键值对总是以字符串的形式存储意味着数值类型会自动转化为字符串类型).

+ +

语法

+ +
myStorage = localStorage;
+ +

+ +

一个可被用于访问当前源( origin )的本地存储空间的 {{domxref("Storage")}} 对象。

+ +

异常

+ +
+
SecurityError
+
请求违反了一个策略声明,或者源( origin )不是 一个有效的 scheme/host/port tuple (例如如果origin使用 file: 或者 data: 形式将可能发生)。比如,用户可以有禁用允许对指定的origin存留数据的浏览器配置。
+
+ +

示例

+ +

下面的代码片段访问了当前域名下的本地 {{domxref("Storage")}} 对象,并通过 {{domxref("Storage.setItem()")}} 增加了一个数据项目。

+ +
localStorage.setItem('myCat', 'Tom');
+
+ +

该语法用于读取 localStorage 项,如下:

+ +
let cat = localStorage.getItem('myCat');
+
+ +

该语法用于移除 localStorage 项,如下:

+ +
localStorage.removeItem('myCat');
+
+ +

该语法用于移除所有的 localStorage 项,如下:

+ +
// 移除所有
+localStorage.clear();
+
+ +
+

注意: 请参考 Using the Web Storage API 的完整示例文章。

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-localstorage', 'localStorage')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.localStorage")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/location/index.html b/files/zh-cn/web/api/window/location/index.html new file mode 100644 index 0000000000..b199786ac8 --- /dev/null +++ b/files/zh-cn/web/api/window/location/index.html @@ -0,0 +1,305 @@ +--- +title: window.location +slug: Web/API/Window/location +tags: + - API + - HTML + - Property + - Reference + - Window + - 'window.location : 所有字母必须小写!' +translation_of: Web/API/Window/location +--- +

{{ APIRef() }}

+ +

window.location 只读属性,返回一个 {{domxref("Location")}}  对象,其中包含有关文档当前位置的信息。

+ +
+

window.location : 所有字母必须小写!

+
+ +

尽管 window.location 是一个只读 Location 对象,你仍然可以赋给它一个 {{domxref("DOMString")}}。这意味着您可以在大多数情况下处理 location,就像它是一个字符串一样:window.location = 'http://www.example.com',是 window.location.href = 'http://www.example.com'的同义词 。

+ +

语法

+ +
let oldLocation = location;
+location = newLocation;
+
+ +

示例

+ +

简单例子

+ +
alert(location);
+// 弹出 "https://developer.mozilla.org/en-US/docs/Web/API/window.location"
+ +

例子#1:导航到一个新页面

+ +

只要赋给 location 对象一个新值,文档就会使用新的 URL 加载,就好像使用修改后的 URL 调用了  window.location.assign() 一样。需要注意的是,安全设置,如 CORS(跨域资源共享),可能会限制实际加载新页面。

+ +
window.location.assign("http://www.mozilla.org"); // or
+window.location = "http://www.mozilla.org";
+
+ +

例子#2:强制从服务器重新加载当前页面

+ +
window.location.reload(true);
+
+ +

例子#3

+ +

考虑下面的例子,该例使用 replace() 方法重新加载页面,并将 window.location.pathname 的值插入到 hash:

+ +
function reloadPageWithHash() {
+  var initialPage = window.location.pathname;
+  window.location.replace('http://example.com/#' + initialPage);
+}
+
+ +
Note: The example above works in situations where window.location.hash does not need to be retained. However, in Gecko-based browsers, setting window.location.pathname in this manner will erase any information in window.location.hash, whereas in WebKit (and possibly other browsers), setting the pathname will not alter the the hash. If you need to change pathname but keep the hash as is, use the replace() method instead, which should work consistently across browsers.
+ +

例子#4:弹出警告框,显示当前 URL 的属性:

+ +
function showLoc() {
+  var oLocation = window.location, aLog = ["Property (Typeof): Value", "window.location (" + (typeof oLocation) + "): " + oLocation ];
+  for (var sProp in oLocation){
+    aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " +  (oLocation[sProp] || "n/a"));
+  }
+  alert(aLog.join("\n"));
+}
+
+// in html: <button onclick="showLoc();">Show location properties</button>
+
+ +

例子#5:通过修改 search 属性向服务器发送字符串数据:

+ +
function sendData (sData) {
+  window.location.search = sData;
+}
+
+// in html: <button onclick="sendData('Some data');">Send data</button>
+
+ +

当前 URL 带上 "?Some%20data",被发送到服务端(如果服务端不处理,则使用修改后的查询字符串 [search string] 重新加载当前文档)。

+ +

例子#6:获取一个 window.location.search 键值(key value):

+ +
function loadPageVar (sVar) {
+  return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
+}
+
+alert(loadPageVar("name"));
+
+ +

例子#7:通过 window.location.search 字符串获取查询参数,存入对象 oGetVars 中:

+ +
var oGetVars = {};
+
+if (window.location.search.length > 1) {
+  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+    aItKey = aCouples[nKeyId].split("=");
+    oGetVars[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
+  }
+}
+
+// alert(oGetVars.yourVar);
+
+ +
 
+ +

同样可以通过一个匿名构造函数来获取,这样只声明了一个全局变量。

+ +
var oGetVars = new (function (sSearch) {
+  if (sSearch.length > 1) {
+    for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+      aItKey = aCouples[nKeyId].split("=");
+      this[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";
+    }
+  }
+})(window.location.search);
+
+// alert(oGetVars.yourVar);
+
+ +

例子#8:通过 window.location.search 字符串获取查询参数,存入对象 oGetVars 中,并尝试识别参数类型typeof):

+ +
var oGetVars = {};
+
+function buildValue(sValue) {
+  if (/^\s*$/.test(sValue)) { return null; }
+  if (/^(true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
+  if (isFinite(sValue)) { return parseFloat(sValue); }
+  if (isFinite(Date.parse(sValue))) { return new Date(sValue); } // this conditional is unreliable in non-SpiderMonkey browsers
+  return sValue;
+}
+
+if (window.location.search.length > 1) {
+  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+    aItKey = aCouples[nKeyId].split("=");
+    oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? buildValue(unescape(aItKey[1])) : null;
+  }
+}
+
+// alert(oGetVars.yourVar);
+
+ +

同样可以通过一个匿名构造函数来获取,这样只声明了一个全局变量。

+ +
var oGetVars = new (function (sSearch) {
+  var rNull = /^\s*$/, rBool = /^(true|false)$/i;
+  function buildValue(sValue) {
+    if (rNull.test(sValue)) { return null; }
+    if (rBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
+    if (isFinite(sValue)) { return parseFloat(sValue); }
+    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
+    return sValue;
+  }
+  if (sSearch.length > 1) {
+    for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+      aItKey = aCouples[nKeyId].split("=");
+      this[unescape(aItKey[0])] = aItKey.length > 1 ? buildValue(unescape(aItKey[1])) : null;
+    }
+  }
+})(window.location.search);
+
+// alert(oGetVars.yourVar);
+
+ +

例子#9:不改变 window.location.hash 属性情况下使用书签

+ +
<!doctype html>
+<html>
+<head>
+<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
+<title>MDN Example</title>
+<script type="text/javascript">
+function showNode (oNode) {
+  var nLeft = 0, nTop = 0;
+  for (var oItNode = oNode; oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent);   window.scrollTo(nLeft, nTop); }
+
+function showBookmark (sBookmark, bUseHash) {
+  if (arguments.length === 1 || bUseHash) { window.location.hash = sBookmark; return; }
+  var oBookmark = document.querySelector(sBookmark);
+  if (oBookmark) { showNode(oBookmark); }
+}
+</script>
+<style type="text/css">
+span.intLink {
+    cursor: pointer;
+    color: #0000ff;
+    text-decoration: underline;
+}
+</style>
+</head>
+
+<body>
+<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>
+<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 bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p>
+<p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');">Go to bookmark #2</span>&nbsp;]</p>
+<p>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. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</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>
+<p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
+<p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante.</p>
+<p>Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.</p>
+<p>Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies.</p>
+<p id="myBookmark2">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');">Go to bookmark #1</span> | <span class="intLink" onclick="showBookmark('#myBookmark1', false);">Go to bookmark #1 without using location.hash</span> | <span class="intLink" onclick="showBookmark('#myBookmark3');">Go to bookmark #3</span>&nbsp;]</p>
+<p>Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius.</p>
+<p>Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in.</p>
+<p id="myBookmark3"><em>Here is the bookmark #3</em></p>
+<p>Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi.</p>
+<p>Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis.</p>
+<p>Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque.</p>
+<p>Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet.</p>
+<p>Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.</p>
+<p>Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio.</p>
+<p>Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero.</p>
+<p>Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem.</p>
+<p>Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis.</p>
+<p>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.</p>
+</body>
+</html>
+
+ +
Note: The function showNode is also an example of the use of the for cycle without a statementsection. In this case a semicolon is always put immediately after the declaration of the cycle.
+ +

下面代码做同样的事,但是页面滚动带有动画效果:

+ +
var showBookmark = (function () {
+  var  _useHash, _scrollX, _scrollY, _nodeX, _nodeY, _itFrame, _scrollId = -1, _bookMark,
+       /*
+       * nDuration: the duration in milliseconds of each frame
+       * nFrames: number of frames for each scroll
+       */
+       nDuration = 200, nFrames = 10;
+
+  function _next () {
+    if (_itFrame > nFrames) { clearInterval(_scrollId); _scrollId = -1; return; }
+    _isBot = true;
+    document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / nFrames);
+    document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames);
+    if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; }
+    _itFrame++;
+  }
+
+  function _chkOwner () {
+    if (_isBot) { _isBot = false; return; }
+    if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; }
+  }
+
+  if (window.addEventListener) { window.addEventListener("scroll", _chkOwner, false); }
+  else if (window.attachEvent) { window.attachEvent("onscroll", _chkOwner); }
+
+  return function (sBookmark, bUseHash) {
+    _scrollY = document.documentElement.scrollTop;
+    _scrollX = document.documentElement.scrollLeft;
+    _bookMark = sBookmark;
+    _useHash = arguments.length === 1 || bUseHash;
+    for (
+      var nLeft = 0, nTop = 0, oNode = document.querySelector(sBookmark);
+      oNode;
+      nLeft += oNode.offsetLeft, nTop += oNode.offsetTop, oNode = oNode.offsetParent
+    );
+    _nodeX = nLeft, _nodeY = nTop, _itFrame = 1;
+    if (_scrollId === -1) { _scrollId = setInterval(_next, Math.round(nDuration / nFrames)); }
+  };
+})();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Window.location")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Window.location")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.location")}}

+ +
 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/locationbar/index.html b/files/zh-cn/web/api/window/locationbar/index.html new file mode 100644 index 0000000000..a1b3af3db5 --- /dev/null +++ b/files/zh-cn/web/api/window/locationbar/index.html @@ -0,0 +1,63 @@ +--- +title: Window.locationbar +slug: Web/API/Window/locationbar +translation_of: Web/API/Window/locationbar +--- +
{{APIRef}}
+ +

概要

+ +

返回一个可以检查visibility属性的 locationbar 对象。

+ +

语法

+ +
objRef = window.locationbar 
+ +

示例

+ +

以下完整的HTML示例显示了使用locationbar对象的visible属性的方式.

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>Various DOM Tests</title>
+
+<script>
+var visible = window.locationbar.visible;
+</script>
+
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-locationbar', 'Window.locationbar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/matchmedia/index.html b/files/zh-cn/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..48abe41c6a --- /dev/null +++ b/files/zh-cn/web/api/window/matchmedia/index.html @@ -0,0 +1,102 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +translation_of: Web/API/Window/matchMedia +--- +

{{APIRef}}

+ +

{{domxref("Window")}} 的matchMedia() 方法返回一个新的{{domxref("MediaQueryList")}} 对象,表示指定的媒体查询字符串解析后的结果。返回的MediaQueryList 可被用于判定{{domxref("Document")}}是否匹配媒体查询,或者监控一个document 来判定它匹配了或者停止匹配了此媒体查询。

+ +

语法

+ +
mqList = window.matchMedia(mediaQueryString)
+
+ +

参数

+ +
+
mediaQueryString
+
一个被用于媒体查询解析的字符串。
+
+ +

返回值

+ +

一个用来媒体查询的新的{{domxref("MediaQueryList")}}对象

+ +

使用说明

+ +

您可以使用返回的媒体查询来执行即时检查和事件驱动检查,以查看文档是否与媒体查询匹配。

+ +

要执行一次瞬时检查以查看文档是否与媒体查询匹配,请查看{{domxref("MediaQueryList.matches", "matches")}}属性的值,当document满足媒体查询条件的时候将会返回true

+ +

如果您需要始终了解document是否与媒体查询匹配,则可以查看将要传递给对象的{{domxref("MediaQueryList.change_event", "change")}} 事件 。{{domxref("Window.devicePixelRatio")}}上的文章中有一个很好的例子。

+ +

举例

+ +

此示例运行媒体查询(max-width: 600px)并在{{HTMLElement("span")}};中显示MediaQueryListmatches属性值。如果视口的宽度小于或等于600像素,则输出将为true,而如果窗口的宽度大于此宽度,则将输出false。

+ +

JavaScript

+ +
let mql = window.matchMedia('(max-width: 600px)');
+
+document.querySelector(".mq-value").innerText = mql.matches;
+
+ +

JavaScript代码只需将要匹配的媒体查询字符串传递到{{domxref("Window.matchMedia", "matchMedia()")}}进行编译,然后设置<span>的{{domxref("HTMLElement.innerText", "innerText")}}为{{domxref("MediaQueryList.media", "matches")}}属性结果的值,以便它表明此document在此刻页面加载完成时是否与媒体查询所匹配。

+ +

HTML

+ +
<span class="mq-value"></span>
+ +

一个简单的 <span> 来接收输出。

+ + + +

Result

+ +

{{EmbedLiveSample("Examples", "100%", "60")}}

+ +

参考更多的例子来 通过代码使用媒体查询

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

浏览器通用性

+ +

{{Compat("api.Window.matchMedia")}}

+ +

请参阅

+ + diff --git a/files/zh-cn/web/api/window/menubar/index.html b/files/zh-cn/web/api/window/menubar/index.html new file mode 100644 index 0000000000..bfd99a1da9 --- /dev/null +++ b/files/zh-cn/web/api/window/menubar/index.html @@ -0,0 +1,57 @@ +--- +title: Window.menubar +slug: Web/API/Window/menubar +translation_of: Web/API/Window/menubar +--- +

{{ APIRef() }}

+ +

概要

+ +

返回一个可以检测visibility属性的 menubar 对象。

+ +

语法

+ +
objRef = window.menubar
+
+ +

示例

+ +

以下完整的HTML示例显示了使用locationbar对象的visible属性的方式。

+ +
<html>
+<head>
+  <title>Various DOM Tests</title>
+  <script>
+    var visible = window.menubar.visible;
+  </script>
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-menubar', 'Window.menubar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-menubar', 'Window.menubar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接:

+ +

window.locationbar, window.personalbar, window.scrollbars, window.statusbar, window.toolbar

diff --git a/files/zh-cn/web/api/window/minimize/index.html b/files/zh-cn/web/api/window/minimize/index.html new file mode 100644 index 0000000000..64c28da15c --- /dev/null +++ b/files/zh-cn/web/api/window/minimize/index.html @@ -0,0 +1,6 @@ +--- +title: window.minimize +slug: Web/API/Window/minimize +translation_of: Web/API/Window/minimize +--- +

{{APIRef}}让当前浏览器窗口最小化(可以通过调用{{ domxref("window.moveTo()") }}方法让窗口恢复正常显示).

diff --git a/files/zh-cn/web/api/window/moveby/index.html b/files/zh-cn/web/api/window/moveby/index.html new file mode 100644 index 0000000000..3e1ad67e96 --- /dev/null +++ b/files/zh-cn/web/api/window/moveby/index.html @@ -0,0 +1,34 @@ +--- +title: Window.moveBy() +slug: Web/API/Window/moveBy +translation_of: Web/API/Window/moveBy +--- +
+ {{APIRef}}
+

概述

+

根据指定的值,移动当前窗口。

+

语法

+
window.moveBy(deltaX, deltaY)
+
+

参数

+ +

示例

+
function budge() {
+  moveBy(10, -10);
+}
+

备注

+

可以使用负值作为该函数的参数。该函数产生相对移动,而 {{domxref("window.moveTo")}} 产生一个绝对移动。

+

从 Firefox 7 开始,依据下面的规则不能再移动一个浏览器里的窗口。

+
    +
  1. 不能移动非 window.open 创建的窗口或 Tab。
  2. +
  3. 当一个窗口里有多于一个 Tab 时,不能移动该窗口。
  4. +
+

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/moveto/index.html b/files/zh-cn/web/api/window/moveto/index.html new file mode 100644 index 0000000000..b817540bc9 --- /dev/null +++ b/files/zh-cn/web/api/window/moveto/index.html @@ -0,0 +1,44 @@ +--- +title: window.moveTo +slug: Web/API/Window/moveTo +translation_of: Web/API/Window/moveTo +--- +
{{ApiRef}}
+ +

概述

+ +

将当前窗口移动到指定的坐标位置。

+ +

语法

+ +
window.moveTo(x, y)
+
+ +

参数

+ + + +

示例

+ +
function origin() {
+  // 把窗口移动到左上角
+  window.moveTo(0, 0);
+}
+ +

附注

+ +

本函数按照指定的绝对位置移动当前窗口,而{{domxref("window.moveBy")}}函数按照与当前位置相对的距离移动当前窗口。

+ +

从Firefox 7开始,如果符合下列情况,则普通网页中的JavaScript无法通过调用该函数来移动浏览器窗口

+ +
    +
  1. 当前窗口或标签页不是由{{domxref("window.open")}}方法创建的
  2. +
  3. 当前标签页所在的窗口包含有多个标签页
  4. +
+ +

规范

+ +

{{dom0}}

diff --git a/files/zh-cn/web/api/window/mozanimationstarttime/index.html b/files/zh-cn/web/api/window/mozanimationstarttime/index.html new file mode 100644 index 0000000000..41666637e4 --- /dev/null +++ b/files/zh-cn/web/api/window/mozanimationstarttime/index.html @@ -0,0 +1,21 @@ +--- +title: window.mozAnimationStartTime +slug: Web/API/Window/mozAnimationStartTIme +translation_of: Web/API/Window/mozAnimationStartTime +--- +

{{ ApiRef() }}

+

{{ gecko_minversion_header("2.0") }}{{ non-standard_header() }}

+

概述

+

Returns the time, in milliseconds since the epoch, at which animations started now should be considered to have started. This value should be used instead of, for example, Date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another.

+

This also allows JavaScript-based animations to remain synchronized with CSS transitions and SMIL animations triggered during the same refresh interval.

+

语法

+
time = window.mozAnimationStartTime;
+
+

规范

+

不属于任何规范.

+

相关链接

+ +

{{ languages( { "en":"en/DOM/window.mozAnimationStartTime" } ) }}

diff --git a/files/zh-cn/web/api/window/mozinnerscreenx/index.html b/files/zh-cn/web/api/window/mozinnerscreenx/index.html new file mode 100644 index 0000000000..4f02d0da11 --- /dev/null +++ b/files/zh-cn/web/api/window/mozinnerscreenx/index.html @@ -0,0 +1,44 @@ +--- +title: Window.mozInnerScreenX +slug: Web/API/Window/mozInnerScreenX +tags: + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Window + - 参考 + - 属性 + - 接口 +translation_of: Web/API/Window/mozInnerScreenX +--- +
{{APIRef}}{{gecko_minversion_header("1.9.2")}}
+ +

概要

+ +

在屏幕坐标中获取窗口视口左上角的X坐标

+ +
备注: 该坐标以CSS像素报告显示,而不是硬件像素。 这意味着它可以受缩放级别的影响; 要计算物理屏幕像素的实际数量,需要使用 nsIDOMWindowUtils.screenPixelsPerCSSPixel 属性.
+ +

语法

+ +
screenX = window.mozInnerScreenX;
+ +

+ + + +

规范

+ +

不属于任何W3C规范或标准.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/mozinnerscreeny/index.html b/files/zh-cn/web/api/window/mozinnerscreeny/index.html new file mode 100644 index 0000000000..f5b5aedb89 --- /dev/null +++ b/files/zh-cn/web/api/window/mozinnerscreeny/index.html @@ -0,0 +1,44 @@ +--- +title: Window.mozInnerScreenY +slug: Web/API/Window/mozInnerScreenY +tags: + - HTML DOM + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Window + - 参考 + - 属性 + - 接口 +translation_of: Web/API/Window/mozInnerScreenY +--- +
{{APIRef}}{{gecko_minversion_header("1.9.2")}}
+ +

概要

+ +

在屏幕坐标下获取窗口视口左上角的Y坐标

+ +
备注:该坐标是以CSS像素报告显示的,而不是以硬件像素。 这意味着它可以受缩放级别的影响; 要计算物理屏幕像素的实际数量,需要使用nsIDOMWindowUtils.screenPixelsPerCSSPixel 属性
+ +

语法

+ +
screenY = window.mozInnerScreenY;
+ +

+ + + +

规范

+ +

不属于任何W3C规范或标准

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/mozpaintcount/index.html b/files/zh-cn/web/api/window/mozpaintcount/index.html new file mode 100644 index 0000000000..da91c15ba4 --- /dev/null +++ b/files/zh-cn/web/api/window/mozpaintcount/index.html @@ -0,0 +1,21 @@ +--- +title: Window.mozPaintCount +slug: Web/API/Window/mozPaintCount +translation_of: Web/API/Window/mozPaintCount +--- +
{{APIRef}} {{gecko_minversion_header("2.0")}}
+ +

返回当前文档渲染到屏幕上所需的时间。

+ +

语法

+ +
var paintCount = window.mozPaintCount;
+ + + +

说明

+ +

不是任何W3C技术规范或建议的一部分。

diff --git a/files/zh-cn/web/api/window/name/index.html b/files/zh-cn/web/api/window/name/index.html new file mode 100644 index 0000000000..820c916235 --- /dev/null +++ b/files/zh-cn/web/api/window/name/index.html @@ -0,0 +1,66 @@ +--- +title: Window.name +slug: Web/API/Window/name +tags: + - API + - NeedsUpdate + - 参考 + - 属性 +translation_of: Web/API/Window/name +--- +
{{APIRef}}
+ +

获取/设置窗口的名称。

+ +

语法

+ +
string = window.name;
+window.name = string;
+ +

示例

+ +
window.name = "lab_view";
+ +

备注

+ +

窗口的名字主要用于为超链接和表单设置目标(targets)。窗口不需要有名称。

+ +

在某些框架里(如,SessionVars 和 Dojo's dojox.io.windowName ,该属性也被用于作为 JSONP 的一个更安全的备选,来提供跨域通信(cross-domain messaging)。现代 web 应用应使用 postMessage API 进行敏感的跨域通信。

+ +

window.name 会调用 toString 将赋给它的值转换成对应的字符串表示。

+ +

(译注:此处似有不妥,私以为调用的应是 ToString 抽象方法。事实上,如果将一个Symbol类型的值赋给 window.name,会报 TypeError,而非调用 Symbol.toString() 转换成字符串后进行赋值。例如:

+ +
window.name = Symbol.for('foo'); // TypeError
+window.name = Symbol.for('foo').toString(); // "Symbol(foo)"
+
+ +

具体可参见EMCA语言规范中Type Conversion一节。)

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('HTML WHATWG', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-name', 'Window.name')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.name")}}

diff --git a/files/zh-cn/web/api/window/navigator/index.html b/files/zh-cn/web/api/window/navigator/index.html new file mode 100644 index 0000000000..0eaf8c6e51 --- /dev/null +++ b/files/zh-cn/web/api/window/navigator/index.html @@ -0,0 +1,94 @@ +--- +title: window.navigator +slug: Web/API/Window/navigator +tags: + - API + - Window + - 只读属性 + - 属性 +translation_of: Web/API/Window/navigator +--- +
{{ApiRef}}
+ +

只读属性 Window.navigator 会返回一个 {{domxref("Navigator")}} 对象的引用,可以用于请求运行当前代码的应用程序的相关信息。

+ +

语法

+ +
navigatorObject = window.navigator
+ +

例子

+ +

例子 #1:检测浏览器并返回浏览器名称字符串

+ +
var sBrowser, sUsrAg = navigator.userAgent;
+
+// The order matters here, and this may report false positives for unlisted browsers.
+
+if (sUsrAg.indexOf("Firefox") > -1) {
+  sBrowser = "Mozilla Firefox";
+  // "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
+} else if (sUsrAg.indexOf("Opera") > -1 || sUsrAg.indexOf("OPR") > -1) {
+  sBrowser = "Opera";
+  //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.106"
+} else if (sUsrAg.indexOf("Trident") > -1) {
+  sBrowser = "Microsoft Internet Explorer";
+  // "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Zoom 3.6.0; wbx 1.0.0; rv:11.0) like Gecko"
+} else if (sUsrAg.indexOf("Edge") > -1) {
+  sBrowser = "Microsoft Edge";
+  // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
+} else if (sUsrAg.indexOf("Chrome") > -1) {
+  sBrowser = "Google Chrome or Chromium";
+  // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/66.0.3359.181 Chrome/66.0.3359.181 Safari/537.36"
+} else if (sUsrAg.indexOf("Safari") > -1) {
+  sBrowser = "Apple Safari";
+  // "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1 980x1306"
+} else {
+  sBrowser = "unknown";
+}
+
+alert("当前浏览器为: " + sBrowser);
+
+ +

例子 #2:检测浏览器并返回代表当前浏览器的索引数字

+ +
function getBrowserId () {
+  var aKeys = ["MSIE", "Firefox", "Safari", "Chrome", "Opera"],
+      sUsrAg = navigator.userAgent,
+      nIdx = aKeys.length - 1;
+
+  for (nIdx; nIdx > -1 && sUsrAg.indexOf(aKeys[nIdx]) === -1; nIdx--);
+
+  return nIdx;
+}
+
+console.log(getBrowserId());
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-navigator', 'Window: navigator')}}{{Spec2('HTML WHATWG')}} 
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.navigator")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/offline_event/index.html b/files/zh-cn/web/api/window/offline_event/index.html new file mode 100644 index 0000000000..7b1886ceaa --- /dev/null +++ b/files/zh-cn/web/api/window/offline_event/index.html @@ -0,0 +1,63 @@ +--- +title: offline +slug: Web/API/Window/offline_event +translation_of: Web/API/Window/offline_event +--- +

当浏览器失去网络连接时,offline事件被触发。并且navigator.onLine的值变为 false

+ +

常规信息

+ +
+
规范
+
HTML5 Offline
+
接口
+
Event
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
当前网页(<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}产生该事件的对象(DOM树中最顶级的那个对象).
type {{readonlyInline}}{{domxref("DOMString")}}事件类型.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}该事件是否冒泡.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}该事件是否可取消默认行为.
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/onappinstalled/index.html b/files/zh-cn/web/api/window/onappinstalled/index.html new file mode 100644 index 0000000000..bbf2065738 --- /dev/null +++ b/files/zh-cn/web/api/window/onappinstalled/index.html @@ -0,0 +1,100 @@ +--- +title: Window.onappinstalled +slug: Web/API/Window/onappinstalled +translation_of: Web/API/Window/onappinstalled +--- +
{{APIRef}}
+ +

{{domxref("Window")}} 对象的 onappinstalled 属性用于处理 {{Event("appinstalled")}}  事件,该事件是一个实现了 {{domxref("Event")}}接口的简单事件,会在网页应用成功安装为渐进式网页应用时立即触发。

+ +

语法

+ +
window.onappinstalled = function(event) { ... };
+
+ +

示例

+ +
window.onappinstalled = function(ev) {
+  console.log('The application was installed.');
+};
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Manifest', '#onappinstalled-attribute', 'Window.onappinstalled')}}{{Spec2('Manifest')}}Initial specification.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(49)}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(49)}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] This feature is behind a feature preference setting. In about:config, set dom.manifest.onappinstall to true.

+ +

相关文章

+ + diff --git a/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html b/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html new file mode 100644 index 0000000000..e2243375f7 --- /dev/null +++ b/files/zh-cn/web/api/window/onbeforeinstallprompt/index.html @@ -0,0 +1,118 @@ +--- +title: Window.onbeforeinstallprompt +slug: Web/API/Window/onbeforeinstallprompt +tags: + - Window.onbeforeinstallprompt + - beforeinstallprompt +translation_of: Web/API/Window/onbeforeinstallprompt +--- +

{{ ApiRef() }}

+ +

Window.onbeforeinstallprompt 属性是一个事件处理程序, 用于处理一个{{event("beforeinstallprompt")}}, 当一个Web清单存在时,它将在移动设备上发送,但是在提示用户将网站保存到主屏幕之前。

+ +

句法

+ +
window.addEventListener("beforeinstallprompt", function(event) { ... });
+
+window.onbeforeinstallprompt = function(event) { ...};
+ +

范例

+ +

The following example uses the beforeinstallprompt function to verify that it is an appropriate time to display an installation prompt to the user. If it is not, the event is redispatched.

+ +
let isTooSoon = true;
+window.addEventListener("beforeinstallprompt", function(e) {
+  if (isTooSoon) {
+    e.preventDefault(); // Prevents prompt display
+    // Prompt later instead:
+    setTimeout(function() {
+      isTooSoon = false;
+      e.prompt(); // Shows prompt
+    }, 10000);
+  }
+
+  // The event was re-dispatched in response to our request
+  // ...
+});
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatNo() }}{{CompatChrome(45.0)}} [1]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatChrome(45.0)}} [1]
+
+ +

[1] Behind the flagchrome://flags/#bypass-app-banner-engagement-checks

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Manifest', '#onbeforeinstallprompt-attribute', 'Window.onbeforeinstallprompt')}}{{Spec2('Manifest')}}Initial specification.
+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/onbeforeunload/index.html b/files/zh-cn/web/api/window/onbeforeunload/index.html new file mode 100644 index 0000000000..78bed99eb9 --- /dev/null +++ b/files/zh-cn/web/api/window/onbeforeunload/index.html @@ -0,0 +1,111 @@ +--- +title: window.onbeforeunload +slug: Web/API/Window/onbeforeunload +translation_of: Web/API/WindowEventHandlers/onbeforeunload +--- +
{{ApiRef}}
+ +

概述

+ +

当窗口即将被{{domxref("window.onunload","卸载(关闭)")}}时,会触发该事件.此时页面文档依然可见,且该事件的默认动作可以被{{domxref("event.preventDefault","取消")}}.

+ +

语法

+ +
window.onbeforeunload = funcRef
+ + + +

示例

+ +
window.onbeforeunload = function (e) {
+  e = e || window.event;
+
+  // 兼容IE8和Firefox 4之前的版本
+  if (e) {
+    e.returnValue = '关闭提示';
+  }
+
+  // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
+  return '关闭提示';
+};
+
+ +

附注

+ +

当该事件返回的字符串(事前设置好的event.returnValue的值)不为null或者undefined时,弹出确认窗口让用户自行选择是否关闭当前页面。一些浏览器将该事件返回的字符串显示在弹出窗上。从Firefox 4、 Chrome 51、Opera 38 和Safari 9.1开始,通用确认信息代替事件返回的字符串。比如,火狐上会显示“本页面要求您确认您要离开 - 您输入的数据可能不会被保存”,请查阅{{bug("588292")}}和Chrome Platform Status

+ +

从2011年5月25日起,  HTML5 规范 声明:在该事件的处理函数中调用下列弹窗相关的方法时,可以忽略不执行,window.showModalDialog(), window.alert(), window.confirm() window.prompt().

+ +

需要指出的是,许多浏览器会忽略该事件并自动关闭页面无需用户的确认。火狐浏览器在配置页面about:config设有一个dom.disable_beforeunload的开关变量用于开启这个功能。

+ +

你可以通过{{domxref("EventTarget.addEventListener","window.addEventListener()")}} 或者 {{event("beforeunload")}} 创建该事件。更多信息请点击以上链接。

+ +

创建这个事件能防止浏览器缓存部分由javascript产生的页面内容。在页面中含Javascript产生的内容情形下,再次导航返回到原页面javascript不在运行。如果事先有window.onbeforeunload事件,导航返回到先前的页面后javascript将被触发并更新页面内容。

+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support114123
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

规范

+ +

该事件最初是由微软公司的IE4引进,虽然没有公开的规范说明,但所有浏览器都支持该事件.目前已被添加至HTML5规范草案中.

+ + + +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/ondevicelight/index.html b/files/zh-cn/web/api/window/ondevicelight/index.html new file mode 100644 index 0000000000..4997722c37 --- /dev/null +++ b/files/zh-cn/web/api/window/ondevicelight/index.html @@ -0,0 +1,105 @@ +--- +title: Window.ondevicelight +slug: Web/API/Window/ondevicelight +tags: + - 实验中 + - 属性 + - 引用 + - 接口 + - 环境光事件 +translation_of: Web/API/Window/ondevicelight +--- +
{{APIRef}}
+ +
声明一个事件监听用以接收{{event("devicelight")}}事件。事件在设备的光传感器检测到周围环境光的强度发生变化时触发。
+ +

语法

+ +
window.ondevicelight = funcRef
+ +

当{{event("devicelight")}}事件触发时,调用funcRef函数。这些事件皆为 {{domxref("DeviceLightEvent")}}事件类型。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('AmbientLight', '#event-handlers', 'Ambient Light Events')}}{{Spec2('AmbientLight')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] 事件{{event("devicelight")}} 的使用最先被实现应用在Android (15.0) 的移动端火狐浏览器和火狐操作系统(B2G)。从 Gecko 22.0 {{geckoRelease("22.0")}}开始,面向Mac OS X 的桌面应用也已实现。目前对Windows 7的支持还在进行中(详见 {{bug(754199)}})。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/ondevicemotion/index.html b/files/zh-cn/web/api/window/ondevicemotion/index.html new file mode 100644 index 0000000000..41cda848df --- /dev/null +++ b/files/zh-cn/web/api/window/ondevicemotion/index.html @@ -0,0 +1,57 @@ +--- +title: Window.ondevicemotion +slug: Web/API/Window/ondevicemotion +tags: + - API + - Device Orientation + - Firefox OS + - Mobile + - Motion + - 移动端设备 +translation_of: Web/API/Window/ondevicemotion +--- +

{{ ApiRef() }}

+ +

摘要

+ +

一个发送到窗口的{{ event("devicemotion")}}事件处理程序。

+ +

语法

+ +
window.ondevicemotion = funcRef;
+
+ +

Where funcRef is a reference to a function. This function receives a {{ domxref("DeviceMotionEvent") }} object describing the motion that occurred.

+ +

这里的funcRef是一个函数的引用。这个函数接收一个{{ domxref("DeviceMotionEvent") }} 对象类型的参数描述发生的动作。

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容

+ +

{{ page("/en-US/docs/Web/API/DeviceMotionEvent","Browser_compatibility") }}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/ondeviceorientation/index.html b/files/zh-cn/web/api/window/ondeviceorientation/index.html new file mode 100644 index 0000000000..672cc0aaa3 --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceorientation/index.html @@ -0,0 +1,47 @@ +--- +title: Window.ondeviceorientation +slug: Web/API/Window/ondeviceorientation +translation_of: Web/API/Window/ondeviceorientation +--- +

{{ ApiRef() }}

+ +

简介

+ +

{{ event("deviceorientation") }}事件的事件处理程序,该事件包含了设备的相对旋转方向改变信息。

+ +

语法

+ +
window.ondeviceorientation = function(event) { ... };
+window.addEventListener('deviceorientation', function(event) { ... });
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

浏览器兼容性

+ +

{{ page("/en-US/docs/Web/API/DeviceOrientationEvent","Browser_compatibility") }}

+ +

更多资料

+ + diff --git a/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html b/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html new file mode 100644 index 0000000000..b595d9852c --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceorientationabsolute/index.html @@ -0,0 +1,35 @@ +--- +title: Window.ondeviceorientationabsolute +slug: Web/API/Window/ondeviceorientationabsolute +translation_of: Web/API/Window/ondeviceorientationabsolute +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

摘要

+ +

An event handler for the {{ event("deviceorientationabsolute") }} event containing information about an absolute device orientation change.

+ +

Syntax

+ +
window.ondeviceorientationabsolute = function(event) { ... };
+window.addEventListener('deviceorientationabsolute', function(event) { ... });
+
+ +

Specifications

+ +

This event handler is not currently part of any specification.

+ +

Browser compatibility

+ + + +

{{Compat("api.Window.ondeviceorientationabsolute")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/ondeviceproximity/index.html b/files/zh-cn/web/api/window/ondeviceproximity/index.html new file mode 100644 index 0000000000..df0a897b1c --- /dev/null +++ b/files/zh-cn/web/api/window/ondeviceproximity/index.html @@ -0,0 +1,93 @@ +--- +title: Window.ondeviceproximity +slug: Web/API/Window/ondeviceproximity +translation_of: Web/API/Window/ondeviceproximity +--- +

{{ ApiRef() }}

+ +

指定一个事件监听器来接受 {{event("deviceproximity")}} 事件,当设备传感器检测到一个对象越来越接近或远离设备时这些事件就会出现。

+ +

语法

+ +
window.onuserproximity = funcRef
+ +

其中funcRef是在发生 {{event("deviceproximity")}} 事件时要调用的函数。这些事件的类型为{{domxref("DeviceProximityEvent")}}。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Proximity Events', '#device-proximity', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatGeckoMobile("15.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/ondragdrop/index.html b/files/zh-cn/web/api/window/ondragdrop/index.html new file mode 100644 index 0000000000..4a99f9da30 --- /dev/null +++ b/files/zh-cn/web/api/window/ondragdrop/index.html @@ -0,0 +1,55 @@ +--- +title: Window.ondragdrop +slug: Web/API/Window/ondragdrop +translation_of: Web/API/Window/ondragdrop +--- +
+

在Firefox 50中已删除,并且从未在任何其他浏览器中实行。 请改用现代标准的HTML5拖放功能。

+
+ +

摘要

+ +

一个事件处理程序,用于将拖放事件发送到窗口。

+ +

语法

+ +
window.ondragdrop = funcRef;
+window.addEventListener("dragdrop", funcRef, useCapturing);
+
+ +
+
funcRef 
+
要注册的事件处理函数。
+
+ +

Gecko({{ Bug(112288) }})中未实现window.ondragdrop属性和ondragdrop属性,您必须使用addEventListener。 有关详细信息,请参见addEventListener

+ +

示例

+ +

在拖放时触发alert

+ +

在此示例中,事件侦听器被添加到窗口(事件目标)。 如果从外部源将选项卡,链接,标记的文本或文件拖放到此窗口上,则会触发警报。 注意event.stopPropagation(); 阻止浏览器加载放置的标签,链接或文件。

+ +
<html>
+<head><title>dragdroptest</title>
+
+<script type="text/javascript">
+
+window.addEventListener("dragdrop", testfunc, false);
+
+function testfunc(event) {
+    alert("dragdrop!");
+    event.stopPropagation();
+}
+</script>
+
+</head>
+<body>
+I am bodytext
+</body>
+</html>
+
+ +

规范

+ +

不属于规范部分。

diff --git a/files/zh-cn/web/api/window/ongamepadconnected/index.html b/files/zh-cn/web/api/window/ongamepadconnected/index.html new file mode 100644 index 0000000000..809fd1f1c7 --- /dev/null +++ b/files/zh-cn/web/api/window/ongamepadconnected/index.html @@ -0,0 +1,64 @@ +--- +title: Window.ongamepadconnected +slug: Web/API/Window/ongamepadconnected +tags: + - API + - Event Handler + - Experimental + - Gamepad API + - Property + - Reference + - Window + - gamepadconnected + - ongamepadconnected + - 手柄 + - 游戏 +translation_of: Web/API/Window/ongamepadconnected +--- +
{{DefaultAPISidebar("Gamepad API")}}{{SeeCompatTable}}
+ +

{{domxref("Window")}} 接口的 ongamepadconnected 属性是一个事件处理程序,它将在游戏手柄连接时运行 (即当 {{event('gamepadconnected')}} 事件触发时)。

+ +

此方法响应的对象类型是 {{domxref("GamepadEvent")}}.

+ +

语法

+ +
window.ongamepadconnected = function() { ... };
+
+ +

示例

+ +
window.ongamepadconnected = function(event) {
+  // 手柄上所有的可用按键和手柄控制元件上各轴向数值都能在此获取
+  event.gamepad;
+};
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Gamepad ', '#event-gamepadconnected', 'gamepadconnected event')}}{{Spec2('Gamepad')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.ongamepadconnected")}}

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/window/ongamepaddisconnected/index.html b/files/zh-cn/web/api/window/ongamepaddisconnected/index.html new file mode 100644 index 0000000000..7712dd6066 --- /dev/null +++ b/files/zh-cn/web/api/window/ongamepaddisconnected/index.html @@ -0,0 +1,51 @@ +--- +title: Window.ongamepaddisconnected +slug: Web/API/Window/ongamepaddisconnected +translation_of: Web/API/Window/ongamepaddisconnected +--- +
{{DefaultAPISidebar("Gamepad API")}}{{SeeCompatTable}}
+ +

The ongamepaddisconnected property of the {{domxref("Window")}} interface represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).

+ +

The event object is of type {{domxref("GamepadEvent")}}.

+ +

解析

+ +
window.ongamepaddisconnected = function() { ... };
+
+ +

示例

+ +
window.ongamepaddisconnected = function() {
+  // A gamepad has been disconnected
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Gamepad ', '#event-gamepaddisconnected', 'gamepaddisconnected event')}}{{Spec2('Gamepad')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.ongamepaddisconnected")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/window/onhashchange/index.html b/files/zh-cn/web/api/window/onhashchange/index.html new file mode 100644 index 0000000000..0c7f3ebefa --- /dev/null +++ b/files/zh-cn/web/api/window/onhashchange/index.html @@ -0,0 +1,124 @@ +--- +title: window.onhashchange +slug: Web/API/Window/onhashchange +tags: + - HTML-DOM + - Property + - Reference + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +

{{APIRef("HTML DOM")}}

+ +

当 一个窗口的 hash (URL 中 # 后面的部分)改变时就会触发 hashchange 事件(参见 {{domxref("Window.location", "location.hash")}})。

+ +

语法

+ +
window.onhashchange = funcRef;
+
+ +

或者

+ +
<body onhashchange="funcRef();">
+ +

以上操作将覆盖现有的事件处理程序。

+ +

为了添加一个新的事件处理程序,而不覆盖掉已有的其他事件处理程序,可以使用函数 "addEventListener"

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

参数

+ +
+
funcRef
+
对一个函数的引用。
+
+ +

例子

+ +
if ("onhashchange" in window) {
+    alert("该浏览器支持 hashchange 事件!");
+}
+
+function locationHashChanged() {
+    if (location.hash === "#somecoolfeature") {
+        somecoolfeature();
+    }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

hashchange 事件

+ +

hashchange 事件对象有下面两个属性:

+ + + + + + + + + + + + + + + + + + + +
属性类型描述
newURL {{ gecko_minversion_inline("6.0") }}DOMString当前页面新的URL
oldURL {{ gecko_minversion_inline("6.0") }}DOMString当前页面旧的URL
+ +

Workaround for event.newURL and event.oldURL

+ +
//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;
+	});
+}());
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}} 
+ +

浏览器兼容性

+ +

{{Compat("api.WindowEventHandlers.onhashchange")}}

+ + diff --git a/files/zh-cn/web/api/window/online_event/index.html b/files/zh-cn/web/api/window/online_event/index.html new file mode 100644 index 0000000000..ecaccec4f7 --- /dev/null +++ b/files/zh-cn/web/api/window/online_event/index.html @@ -0,0 +1,65 @@ +--- +title: online +slug: Web/API/Window/online_event +translation_of: Web/API/Window/online_event +--- +

当浏览器能够访问网络, 并且navigator.online的值被设为true时, online事件被触发.

+ +
注意: 该事件不能用来决定某个网站可否访问.网站自身问题或防火墙或GFW都依然有可能阻止该网站的访问.
+ +

常规信息

+ +
+
规范
+
HTML5 Offline
+
接口
+
Event
+
是否冒泡
+
+
可取消默认行为
+
+
目标对象
+
当前网页(<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
属性类型描述
target {{readonlyInline}}{{domxref("EventTarget")}}产生该事件的对象(DOM树中最顶级的那个对象).
type {{readonlyInline}}{{domxref("DOMString")}}事件类型.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}该事件是否冒泡.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}该事件是否可取消默认行为.
+ +

相关事件

+ + diff --git a/files/zh-cn/web/api/window/onmouseup/index.html b/files/zh-cn/web/api/window/onmouseup/index.html new file mode 100644 index 0000000000..80ec093560 --- /dev/null +++ b/files/zh-cn/web/api/window/onmouseup/index.html @@ -0,0 +1,42 @@ +--- +title: window.onmouseup +slug: Web/API/Window/onmouseup +translation_of: Web/API/GlobalEventHandlers/onmouseup +--- +

{{ ApiRef() }}

+

概述

+

当前窗口的mouseup事件的事件句柄.

+

语法

+
window.onmouseup = funcRef;
+
+

参数

+ +

例子

+
window.onmouseup = doFunc;
+
+
<html>
+<head>
+
+<title>onmouseup测试</title>
+
+<script type="text/javascript">
+
+window.onmouseup = mouseup;
+
+function mouseup()
+{
+ alert("检测到mouseup事件!");
+}
+</script>
+</head>
+
+<body>
+<p>在页面上按下鼠标中某个键,保持几秒后松开.mouseup事件会在你松开鼠标时触发</p>
+</body>
+</html>
+
+

规范

+

没有任何公开的标准

+

{{ languages( { "ja": "ja/DOM/window.onmouseup" ,"en": "en/DOM/window.onmouseup" } ) }}

diff --git a/files/zh-cn/web/api/window/onmozbeforepaint/index.html b/files/zh-cn/web/api/window/onmozbeforepaint/index.html new file mode 100644 index 0000000000..c5206502d7 --- /dev/null +++ b/files/zh-cn/web/api/window/onmozbeforepaint/index.html @@ -0,0 +1,38 @@ +--- +title: Window.onmozbeforepaint +slug: Web/API/Window/onmozbeforepaint +tags: + - API + - Property +translation_of: Web/API/Window/onmozbeforepaint +--- +

{{ ApiRef() }}

+ +

{{ obsolete_header("11") }}{{ non-standard_header() }}

+ +
警告: 这个非标准时间处理器在某些已发布版本中无法使用,而且已经在Gecko 11.0 中被移除{{ geckoRelease("11.0") }}。
+ +

摘要

+ +

MozBeforePaints 事件的事件处理器. 这样做是为了保持和 {{ domxref("window.mozRequestAnimationFrame()") }}方法一致以期在JavaScript代码中提供流畅,同步的动画。

+ +

语法

+ +
window.onmozbeforepaint = funcRef;
+
+ + + +

例子

+ +

请查看{{ domxref("window.mozRequestAnimationFrame()") }}。

+ +

注意

+ +

这个事件会在浏览器重绘前立即触发,如果事件被一个或多个代码调用响应{{domxref("window.mozRequestAnimationFrame()") }}。事件处理器会接收到一个事件作为输入参数,其 timeStamp 属性为UTC起始到现在的毫秒数字,这是当前动画帧的“当前时间”。这个时间对于所有在相同浏览器窗口运行的,包括哪些用了 {{ domxref("window.mozRequestAnimationFrame()") }} 方法,CSS transitions, 和 SMIL animations的都是一样的。

+ +

说明

+ +

没有特别的说明。

diff --git a/files/zh-cn/web/api/window/onpaint/index.html b/files/zh-cn/web/api/window/onpaint/index.html new file mode 100644 index 0000000000..3422b02f71 --- /dev/null +++ b/files/zh-cn/web/api/window/onpaint/index.html @@ -0,0 +1,31 @@ +--- +title: Window.onpaint +slug: Web/API/Window/onpaint +translation_of: Web/API/Window/onpaint +--- +

{{ ApiRef() }}

+ +

{{Non-standard_header}}

+ +

总结

+ +

window中的paint事件处理,目前在Gecko-based(火狐)应用中不被支持,参见【注意事项】部分的说明。

+ +

语法

+ +
window.onpaint =funcRef;
+
+ + + +

注意事项

+ +

onpaint 现在没有生效,并且这个事件是否会生效也是一个问题,参见{{Bug(239074)}}.

+ +

window渲染时paint事件会触发。此事件在window的load事件之后触发,并且每次window需要重绘时都会再次触发,当另一个window出现使原先的window不处于激活状态时,原window的onpaint事件则被清理。

+ +

规范

+ +

不是任何规范的一部分.

diff --git a/files/zh-cn/web/api/window/onpopstate/index.html b/files/zh-cn/web/api/window/onpopstate/index.html new file mode 100644 index 0000000000..6efc1ec835 --- /dev/null +++ b/files/zh-cn/web/api/window/onpopstate/index.html @@ -0,0 +1,68 @@ +--- +title: window.onpopstate +slug: Web/API/Window/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +

{{ ApiRef() }}

+ +

{{ gecko_minversion_header("2") }}

+ +

概述

+ +

window.onpopstatepopstate事件在window对象上的事件处理程序.

+ +

每当处于激活状态的历史记录条目发生变化时,popstate事件就会在对应window对象上触发. 如果当前处于激活状态的历史记录条目是由history.pushState()方法创建,或者由history.replaceState()方法修改过的, 则popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝.

+ +

注意:调用history.pushState()或者history.replaceState()不会触发popstate事件. popstate事件只会在浏览器某些行为下触发, 比如点击后退、前进按钮(或者在JavaScript中调用history.back()、history.forward()、history.go()方法),此外,a 标签的锚点也会触发该事件.

+ +

当网页加载时,各浏览器对popstate事件是否触发有不同的表现,Chrome 和 Safari会触发popstate事件, 而Firefox不会.

+ +

语法

+ +
window.onpopstate = funcRef;
+
+ + + +

popstate事件

+ +

假如当前网页地址为http://example.com/example.html,则运行下述代码后:

+ +
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}
+
+ +

即便进入了那些非pushState和replaceState方法作用过的(比如http://example.com/example.html)没有state对象关联的那些网页, popstate事件也仍然会被触发.

+ +

规范

+ + + +

浏览器兼容性

+ + + +

{{Compat("api.WindowEventHandlers.onpopstate")}}

+ +

相关链接

+ + + +

{{ languages( {"en": "en/DOM/window.onpopstate" } ) }}

diff --git a/files/zh-cn/web/api/window/onscroll/index.html b/files/zh-cn/web/api/window/onscroll/index.html new file mode 100644 index 0000000000..3d6a7bfdb6 --- /dev/null +++ b/files/zh-cn/web/api/window/onscroll/index.html @@ -0,0 +1,53 @@ +--- +title: window.onscroll +slug: Web/API/Window/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +

{{ ApiRef() }}

+

概述

+

为当前页面的页面滚动事件添加事件处理函数.

+

语法

+
window.onscroll = funcRef;
+
+ +

例子

+
window.onscroll = function (e) {
+  // 当页面的滚动条滚动时,会执行这里的代码
+}
+
+
<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>
+
+

备注

+

{{ Bug("189308") }}, 在旧版本的Gecko中(Gecko 1.8/Firefox 1.5之前), scroll 事件只会在用户拖动滚动条时发生,使用方向键和鼠标滚轮滚动页面则不会触发该事件.

+

当 window.scrollX/scrollY 不为 0时,意味着用户或者网页脚本已经执行了窗口的滚动行为.

+

规范

+ +

{{ languages( { "en": "en/DOM/window.onscroll"} ) }}

diff --git a/files/zh-cn/web/api/window/onunload/index.html b/files/zh-cn/web/api/window/onunload/index.html new file mode 100644 index 0000000000..5e766c1d67 --- /dev/null +++ b/files/zh-cn/web/api/window/onunload/index.html @@ -0,0 +1,69 @@ +--- +title: window.onunload +slug: Web/API/Window/onunload +translation_of: Web/API/WindowEventHandlers/onunload +--- +

{{ ApiRef("HTML DOM") }}

+ +

概述

+ +

{{domxref("WindowEventHandlers")}} 的混入特性 onunload 是 {{domxref("EventHandler")}}  处理 {{Event("unload")}} 事件的方法。该事件在关闭窗口资源和内容的时候触发。页面资源的清除工作会在 unload  事件之后进行。

+ +
+

注意事项: 具备弹窗阻止功能的浏览器会忽略 onunload  事件回调中调用的 {{domxref("Window.open()")}} 方法。

+
+ +
+

onunload 特性(乃至 unload 事件本身) 并非使用 sendBeacon()的正确途径,要调用 sendBeacon() 接口,应当使用 visibilitychange 和 pagehide 事件。 参见 Beacon API is broken

+
+ +

语法

+ +
window.addEventListener("unload", function(event) { ... });
+window.onunload = function(event) { ... };
+ +

通常而言,我们推荐使用 {{domxref("EventTarget.addEventListener", "window.addEventListener()")}} 来监听 {{event("unload")}} 事件,而不是直接给 onunload 赋值。

+ +

例子

+ +
<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>
+
+
+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( {"en": "en/DOM/window.onunload" } ) }}

+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowEventHandlers.onunload")}}

+ +

在 Firefox 1.5 中,页面使用此事件处理程序会阻止浏览器在 bfcache 内存中缓存页面(译者注:翻译可能没有达意,请对照英文原文)。详细信息请参阅使用 Firefox 1.5:缓存

diff --git a/files/zh-cn/web/api/window/onuserproximity/index.html b/files/zh-cn/web/api/window/onuserproximity/index.html new file mode 100644 index 0000000000..9a4c3a0c7c --- /dev/null +++ b/files/zh-cn/web/api/window/onuserproximity/index.html @@ -0,0 +1,45 @@ +--- +title: Window.onuserproximity +slug: Web/API/Window/onuserproximity +translation_of: Web/API/Window/onuserproximity +--- +

{{ ApiRef() }}

+ +

Window.onuserproxymity 属性代表一个 {{domxref("EventHandler")}}, 当触发 {{event("userproximity")}} 事件时会调用这个函数。这些事件是 {{domxref("UserProximityEvent")}} 类型的,在设备传感器检测到对象变得靠近时触发。

+ +

语法

+ +
window.onuserproximity = eventHandler
+ +

说明

+ + + + + + + + + + + + + + + + +
说明状态评论
{{ SpecName('Proximity Events', '#user-proximity', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+ +

浏览器兼容

+ + + +

{{Compat("api.Window.onuserproximity")}}

+ +

其他

+ + diff --git a/files/zh-cn/web/api/window/open/index.html b/files/zh-cn/web/api/window/open/index.html new file mode 100644 index 0000000000..3080abb470 --- /dev/null +++ b/files/zh-cn/web/api/window/open/index.html @@ -0,0 +1,686 @@ +--- +title: Window.open() +slug: Web/API/Window/open +tags: + - API + - DOM + - NeedsUpdate + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/open +--- +
{{APIRef}}
+ +

Window 接口的 open() 方法,是用指定的名称将指定的资源加载到浏览器上下文(窗口 window ,内嵌框架 iframe 或者标签 tab )。如果没有指定名称,则一个新的窗口会被打开并且指定的资源会被加载进这个窗口的浏览器上下文中。

+ +

语法

+ +

+let windowObjectReference = window.open(strUrl, strWindowName, [strWindowFeatures]);
+ +
+

strUrl === 要在新打开的窗口中加载的URL。

+ +

strWindowName === 新窗口的名称。

+ +

strWindowFeatures === 一个可选参数,列出新窗口的特征(大小,位置,滚动条等)作为一个{{domxref("DOMString")}}。

+
+ +

+ +

参数与返回值

+ +
+
WindowObjectReference
+
打开的新窗口对象的引用。如果调用失败,返回值会是 null 。如果父子窗口满足“同源策略”,你可以通过这个引用访问新窗口的属性或方法。
+
+ +
+
strUrl
+
新窗口需要载入的url地址。strUrl可以是web上的html页面也可以是图片文件或者其他任何浏览器支持的文件格式。
+
+ +
+
strWindowName
+
新窗口的名称。该字符串可以用来作为超链接 {{HTMLElement("a")}} 或表单 {{HTMLElement("form")}} 元素的目标属性值。字符串中不能含有空白字符。注意:strWindowName 并不是新窗口的标题。
+
+ +
+
strWindowFeatures
+
可选参数。是一个字符串值,这个值列出了将要打开的窗口的一些特性(窗口功能和工具栏) 。 字符串中不能包含任何空白字符,特性之间用逗号分隔开。参考下文的位置和尺寸特征
+
+ +

说明

+ +

open() 方法,创建一个新的浏览器窗口对象,如同使用文件菜单中的新窗口命令一样。strUrl 参数指定了该窗口将会打开的地址。如果strUrl 是一个空值,那么打开的窗口将会是带有默认工具栏的空白窗口(加载about:blank)。

+ +

注意:调用window.open()方法以后,远程 URL 不会被立即载入,载入过程是异步的。(实际加载这个URL的时间推迟到当前脚本块执行结束之后。窗口的创建和相关资源的加载异步地进行。)

+ +

例子

+ +
let windowObjectReference;
+let strWindowFeatures = `
+    menubar=yes,
+    location=yes,
+    resizable=yes,
+    scrollbars=yes,
+    status=yes
+`;
+
+function openRequestedPopup() {
+    windowObjectReference =
+    window.open(
+        "http://www.cnn.com/",
+        "CNN_WindowName",
+        strWindowFeatures
+    );
+}
+ +
let WindowObjectReference;
+
+const openRequestedPopup = () => {
+    windowObjectReference = window.open(
+        "https://www.domainname.ext/path/ImageFile.png",
+        "DescriptiveWindowName",
+        "resizable,scrollbars,status"
+    );
+}
+
+ +

如果已经存在以 strWindowName 为名称的窗口,则不再打开一个新窗口,而是把 strUrl 加载到这个窗口中。在这种情况下,方法的返回值是这个已经打开的窗口,并忽略参数 strWindowFeaturesstrUrl设为空字符串时,可以在不改变窗口地址的情况下获得一个已经打开的同名窗口的引用。如果要在每次调用 window.open()时都打开一个新窗口,则要把参数 strWindowName 设置为 _blank

+ +

strWindowFeatures 是一个可选的字符串,包含了新窗口的一组用逗号分割的特性,在窗口打开之后,就不能用JavaScript改变窗口的功能和工具栏的设置。如果名称是 strWindowName 的窗口不存在并且又没有提供 strWindowFeatures 参数(或者 strWindowFeatures 参数为空字符串),则子窗口以父窗口默认的工具栏渲染。

+ +

如果 strWindowFeatures 参数中没有定义窗口大小,则新窗口的尺寸跟最近渲染的窗口尺寸一样。

+ +

如果 strWindowFeatures 参数中没有定义窗口位置,则新窗口显示在最近渲染的窗口的坐标偏移22个像素的位置。这种新窗口偏移量的做法被浏览器开发商广泛地实现(MSIE 6 SP2在默认主题下的偏移量是29个像素),目的是提醒用户注意有新的窗口打开。如果最近使用的窗口是最大化的,则没有这22像素的偏移,新(子)窗口也会被最大化。

+ +

如果你定义了 strWindowFeatures 参数,那么没有在这个字符串中列出的特性会被禁用或移除 (除了 titlebarclose 默认设置为yes)

+ +
+

提示: 如果你使用了 strWindowFeatures 参数,那么只需要列出新窗口中启用的特性,其它的特性(除了titlebarclose)将被禁用或移除。

+
+ +

Firefox Chrome Toolbars Illustration

+ +

位置尺寸特征

+ +

+ +
{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}
+ +

Note on position and dimension error correction

+ +
{{bug(176320)}}
+ +

Note on precedence

+ +
+
left
+
Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
top
+
Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
height
+
Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
width
+
Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
screenX
+
Deprecated. Same as left but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
screenY
+
Deprecated. Same as top but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
centerscreen
+
Centers the window in relation to its parent's size and position. Requires chrome=yes.
+
outerHeight
+
Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.
+
Note: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
outerWidth
+
Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerHeight
+
Same as height but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The innerHeight value includes the height of the horizontal scrollbar if present. Minimal required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerWidth
+
Same as width but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Toolbar and chrome features

+ +
+
NOTE: All features can be set to yes, 1 or just be present to be "on", set to no oror in most cases just not present to be "off"
+
example "status=yes", "status=1" and "status" have identical results
+
+
menubar
+
If this feature is on, then the new secondary window renders the menubar.
+
Mozilla and Firefox users can force new windows to always render the menubar by setting dom.disable_window_open_feature.menubar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
toolbar
+
If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to no all toolbars in the window will be invisible, for example extension toolbars).
+
Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting dom.disable_window_open_feature.toolbar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
location
+
If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.
+
Mozilla and Firefox users can force new windows to always render the location bar by setting dom.disable_window_open_feature.location to true in about:config or in their user.js file. {{Fx_minversion_note(3, "In Firefox 3, dom.disable_window_open_feature.location now defaults to true, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
personalbar
+
If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.
+
Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
directories {{obsolete_inline("2")}}
+
Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.
+
status
+
If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (Note on status bar in XP SP2) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.
+
Note on status bar
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Window functionality features

+ +
+
+
attention {{NonStandardBadge}}
+
If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/docs/Archive/B2G_OS/Firefox_OS_apps/App_permissions", "Internal (Certified) app permissions")}} for more information.
+
Supported in:
+
dependent
+
If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.
+
Dependent windows are not implemented on MacOS X, this option will be ignored.
+
The dependent feature is currently under revision to be removed ({{Bug(214867)}})
+
In MSIE 6, the nearest equivalent to this feature is the showModelessDialog() method.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
dialog
+
MenuSystemCommands.pngThe dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
minimizable
+
This setting can only apply to dialog windows; "minimizable" requires dialog=yes. If minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no will be ignored.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
fullscreen
+
Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.
+
This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.
+
fullscreen always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.
+
Note on fullscreen
+
Supported in: Internet Explorer 5+
+
fullscreen does not really work in MSIE 6 SP2.
+
resizable
+
If this feature is on, the new secondary window will be resizable.
+
Note: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. +

Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})

+ +
+

Tip: For accessibility reasons, it is strongly recommended to set this feature always on

+
+
+
Mozilla and Firefox users can force new windows to be easily resizable by setting
+ dom.disable_window_open_feature.resizable
+ to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
scrollbars
+
If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. +
+

Tip: For accessibility reasons, it is strongly encouraged to set this feature always on.

+
+
+
Mozilla and Firefox users can force this option to be always enabled for new windows by setting
+ dom.disable_window_open_feature.scrollbars
+ to true in about:config or in their user.js file.
+
Note on scrollbars
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Features requiring privileges

+ +

The following features require the UniversalBrowserWrite privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.

+ +
+
chrome
+
Note: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the UniversalBrowserWrite privilege ({{Bug(244965)}}). Without this privilege, it is ignored.
+
If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
modal
+
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ({{Bug(180048)}}). Without this privilege, it is ignored.
+
If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
+
The exact behavior of modal windows depends on the platform and on the Mozilla release version. +
+

Note: As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.

+
+
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
titlebar
+
By default, all new secondary windows have a titlebar. If set to no or 0, this feature removes the titlebar from the new secondary window.
+
Mozilla and Firefox users can force new windows to always render the titlebar by setting
+ dom.disable_window_open_feature.titlebar
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysRaised
+
If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysLowered
+
If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
z-lock
+
Same as alwaysLowered.
+
close
+
When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes.
+
Mozilla and Firefox users can force new windows to always have a close button by setting
+ dom.disable_window_open_feature.close
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a yes or no; you can use 1 instead of yes and 0 instead of no. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the features string. If you supply the features parameter, then the titlebar and close are still yes by default, but the other features which have a yes/no choice will be no by default and will be turned off.

+ +

Example:

+ +
var windowObjectReference; // global variable
+
+function openRequestedPopup() {
+  windowObjectReference = window.open(
+    "http://www.domainname.ext/path/ImgFile.png",
+    "DescriptiveWindowName",
+    "width=420,height=230,resizable,scrollbars=yes,status=1"
+  );
+}
+ +
+ +

In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.

+ +

Best practices

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openFFPromotionPopup() {
+  if(windowObjectReference == null || windowObjectReference.closed)
+  /* if the pointer to the window object in memory does not exist
+     or if such pointer exists but the window was closed */
+
+  {
+    windowObjectReference = window.open("http://www.spreadfirefox.com/",
+   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
+    /* then create it. The new window will be created and
+       will be brought on top of any other window. */
+  }
+  else
+  {
+    windowObjectReference.focus();
+    /* else the window reference must exist and the window
+       is not closed; therefore, we can bring it back on top of any other
+       window with the focus() method. There would be no need to re-create
+       the window or to reload the referenced resource. */
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindowName"
+ onclick="openFFPromotionPopup(); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+ +
+ +
+ +

The above code solves a few usability problems related to links opening secondary window. The purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".

+ +

More reading on the use of the target attribute:

+ +

HTML 4.01 Target attribute specifications

+ +

How do I create a link that opens a new window?

+ +

You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openRequestedPopup(strUrl, strWindowName) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, strWindowName,
+           "resizable,scrollbars,status");
+  } else {
+    windowObjectReference.focus();
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindow"
+ onclick="openRequestedPopup(this.href, this.target); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+ +
+ +

You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+var PreviousUrl; /* global variable which will store the
+                    url currently in the secondary window */
+
+function openRequestedSinglePopup(strUrl) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+         "resizable,scrollbars,status");
+  } else if(PreviousUrl != strUrl) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+      "resizable=yes,scrollbars=yes,status=yes");
+    /* if the resource to load is different,
+       then we load it in the already opened secondary window and then
+       we bring such window back on top/in front of its parent window. */
+    windowObjectReference.focus();
+  } else {
+    windowObjectReference.focus();
+  };
+
+  PreviousUrl = strUrl;
+  /* explanation: we store the current url in order to compare url
+     in the event of another call of this function. */
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+<p><a
+ href="http://www.mozilla.org/support/firefox/faq"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Firefox FAQ</a></p>
+
+ +

FAQ

+ +
+
How can I prevent the confirmation message asking the user whether he wants to close the window?
+
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
+
More on the window.close() method
+
How can I bring back the window if it is minimized or behind another window?
+
First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the focus() method. There is no other reliable way. You can examine an example explaining how to use the focus() method.
+
How do I force a maximized window?
+
You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.
+
How do I turn off window resizability or remove toolbars?
+
You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in about:config. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.
+
How do I resize a window to fit its content?
+
You can not reliably because the users can prevent the window from being resized by unchecking the Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows checkbox in Mozilla or Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows checkbox in Firefox or by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file.
+
In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.
+
The window method sizeToContent() is also disabled if the user unchecks the preference Move or resize existing windows checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.
+
How do I open a referenced resource of a link in a new tab? or in a specific tab?
+
To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently
+
K-meleon 1.1, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.
+
In a few years, the target property of the CSS3 hyperlink module may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.
+
How do I know whether a window I opened is still open?
+
You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that windowObjectReference.closed return value is false.
+
How can I tell when my window was blocked by a popup blocker?
+
With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of window.open(): it will be null if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.
+
What is the JavaScript relationship between the main window and the secondary window?
+
The window.open() method gives a main window a reference to a secondary window; the opener property gives a secondary window a reference to its main window.
+
I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error: uncaught exception: Permission denied to get property <property_name or method_name>. Why is that?
+
It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.
+
More reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html
+
+ +

Usability issues

+ +

Avoid resorting to window.open()

+ +

Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:

+ + + + + +

If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:

+ +

Never use this form of code for links: <a href="javascript:window.open(...)" ...>

+ +

"javascript:" links break accessibility and usability of webpages in every browser.

+ + + +

Further reading:

+ + + +

Never use <a href="#" onclick="window.open(...);">

+ +

Such pseudo-link also breaks accessibility of links. Always use a real URL for the href attribute value so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.

+ + + +

Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.

+ +

The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).

+ +
+

"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button."
+ quote from The Top Ten New Mistakes of Web Design: 2. Opening New Browser Windows, Jakob Nielsen, May 1999

+
+ +

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).

+ +

References

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Example "New Window" Icons & Cursors
New window icon from yahoo.comNew window icon from microsoft.comNew window icon from webaim.orgNew window icon from sun.com
New window icon from bbc.co.ukNew window icon from Accessible Internet SolutionsNew window icon from accessify.comNew window icon from webstyleguide.com
New window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from gtalbot.org
New window cursor from draig.deNew window cursor from mithgol.ru
+ +

Always use the target attribute

+ +

If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.

+ +

Do not use target="_blank"

+ +

Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).

+ +

Glossary

+ +
+
Opener window, parent window, main window, first window
+
Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.
+
Sub-window, child window, secondary window, second window
+
Terms often used to describe or to identify the same window. It is the new window which was created.
+
Unrequested popup windows
+
Script-initiated windows opening automatically without the user's consent.
+
+ +

规范

+ +

HTML5. See http://www.w3.org/TR/html5/browsers.html#dom-open for details.

+ +

注意

+ +

优先注意事项

+ +

In cases where left and screenX (and/or top and screenY) have conflicting values, then left and top have precedence over screenX and screenY respectively. If left and screenX (and/or top and screenY) are defined in the features list, then left (and/or top) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.

+ +
windowObjectReference = window.open(
+  "http://news.bbc.co.uk/",
+  "BBCWorldNewsWindowName",
+  "left=100,screenX=200,resizable,scrollbars,status"
+);
+ +
+ +

If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.

+ +

outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.

+ +
windowObjectReference = window.open(
+  "http://www.wwf.org/",
+  "WWildlifeOrgWindowName",
+  "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status"
+);
+ +
+ +

Note on position and dimension error correction

+ +

Requested position and requested dimension values in the features list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.

+ +

MSIE 6 SP2 has a similar error correction mechanism but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.

+ +

Note on scrollbars

+ +

When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:

+ + + +

Note on status bar

+ +

You should assume that a large majority of users' browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with SSL connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.

+ +

Note on security issues of the status bar presence

+ +

In MSIE 6 for XP SP2: For windows opened using window.open():

+ +
+

"For windows opened using window.open():
+ Expect the status bar to be present, and code for it. The status bar will be on by default and is 20-25 pixels in height. (...)"
+ quote from Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2

+
+ +
+

"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.
+ Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)
+ Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar. (...)
+ Script management of Internet Explorer status bar
+ Detailed description
+ Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows. (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.
+ The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"
+ quote from Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions

+
+ +

Note on fullscreen

+ +

In MSIE 6 for XP SP2:

+ + + +

References:

+ + + +

Note on outerHeight versus height

+ +

innerHeight vs outerHeight illustration

+ +

Note on refreshing vs. opening a new window/tab

+ +

If the strWindowName parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.

+ +
//Always opens a new window/tab
+window.open("map.php");
+
+//Refreshes an existing window/tab that was opened with the same name, if one exists
+window.open("map.php", "BiggerMap");
+
+ +
+ +

教程

+ + + +

参考文献

+ + diff --git a/files/zh-cn/web/api/window/opendialog/index.html b/files/zh-cn/web/api/window/opendialog/index.html new file mode 100644 index 0000000000..80705cd7aa --- /dev/null +++ b/files/zh-cn/web/api/window/opendialog/index.html @@ -0,0 +1,71 @@ +--- +title: window.openDialog +slug: Web/API/Window/openDialog +tags: + - Gecko DOM Reference +translation_of: Web/API/Window/openDialog +--- +

{{ ApiRef() }}

+

简介

+

window.openDialog 是对window.open的扩展。和它一样,可以传递windowFeatures参数, 但是 windowFeatures 的方式有变化。

+

The optional parameters, if present, will be bundled up in a JavaScript Array object and added to the newly created window as a property named window.arguments. They may be referenced in the JavaScript of the window at any time, including during the execution of a load handler. These parameters may be used, then, to pass arguments to and from the dialog window.

+

Note that the call to openDialog() returns immediately. If you want the call to block until the user has closed the dialog, supply modal as a windowFeatures parameter. Note that this also means the user won't be able to interact with the opener window until he closes the modal dialog.

+

语法

+
newWindow = openDialog(url,name,features,arg1,arg2, ...)
+
+
+
+ newWindow 
+
+ 打开的窗口对象。
+
+ url 
+
+ 要在新窗口里打开的地址。
+
+ name 
+
+ The window name (optional). See window.open description for detailed information.
+
+ features 
+
+ See window.open description for description.
+
+ arg1, arg2, ... 
+
+ The arguments to be passed to the new window (optional).
+
+

例子

+
var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+

注意

+

New Features

+

all - Initially activates (or deactivates ("all=no")) all chrome (except the behaviour flags chrome, dialog and modal). These can be overridden (so "menubar=no,all" turns on all chrome except the menubar.) This feature is explicitly ignored by window.open. window.openDialog finds it useful because of its different default assumptions.

+

Default behaviour

+

The chrome and dialog features are always assumed on, unless explicitly turned off ("chrome=no"). openDialog treats the absence of the features parameter as does window.open, (that is, an empty string sets all features to off) except chrome and dialog, which default to on. If the features parameter is a zero-length string, or contains only one or more of the behaviour features (chrome, dependent, dialog and modal) the chrome features are assumed "OS' choice." That is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system.

+

Passing extra parameters to the dialog

+

To pass extra parameters into the dialog, you can simply supply them after the <tt>windowFeatures</tt> parameter:

+
openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+

The extra parameters will then get packed into a property named <tt>arguments</tt> of type Array, and this property gets added to the newly opened dialog window.

+

To access these extra parameters from within dialog code, use the following scheme:

+
var food  = window.arguments[0];
+var price = window.arguments[1];
+
+

Note that you can access this property from within anywhere in the dialog code. (Another example).

+

Returning values from the dialog

+

Since <tt>window.close()</tt> erases all properties associated with the dialog window (i.e. the variables specified in the JavaScript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs).

+

To be able to pass values back to the caller, you have to supply some object via the extra parameters. You can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve past the <tt>window.close()</tt> operation.

+
var retVals = { address: null, delivery: null };
+openDialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retVals);
+
+

If you set the properties of the <tt>retVals</tt> object in the dialog code as described below, you can now access them via the <tt>retVals</tt> array after the <tt>openDialog()</tt> call returns.

+

Inside the dialog code, you can set the properties as follows:

+
var retVals = window.arguments[2];
+retVals.address  = enteredAddress;
+retVals.delivery = "immediate";
+
+

See also . (Another example).

+

Specification

+

{{ DOM0() }}

+

{{ languages( { "pl": "pl/DOM/window.openDialog" } ) }}

diff --git a/files/zh-cn/web/api/window/opener/index.html b/files/zh-cn/web/api/window/opener/index.html new file mode 100644 index 0000000000..52317273f7 --- /dev/null +++ b/files/zh-cn/web/api/window/opener/index.html @@ -0,0 +1,38 @@ +--- +title: window.opener +slug: Web/API/Window/opener +translation_of: Web/API/Window/opener +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回打开当前窗口的那个窗口的引用,例如:在window A中打开了window B,B.opener 返回 A.

+ +

语法

+ +
var objRef = window.opener;
+
+ +

例子

+ +
 if (window.opener != indexWin) {
+     referToTop(window.opener);
+ }
+
+ +

备注

+ +

如果当前窗口是由另一个窗口打开的, window.opener保留了那个窗口的引用. 如果当前窗口不是由其他窗口打开的, 则该属性返回 null.

+ +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "fr": "fr/DOM/window.opener", "ja": "ja/DOM/window.opener", "pl": "pl/DOM/window.opener", "en": "en/DOM/window.opener" } ) }}

+ +

浏览器兼容性

+ +

{{Compat("api.Window.opener")}}

+ +

注意:在Chrome78最近的几个版本,如果A、B页面跨域,A页面中打开B页面,在B页面使用console.log在控制台打印window.opener会报跨域的错误。

diff --git a/files/zh-cn/web/api/window/orientationchange_event/index.html b/files/zh-cn/web/api/window/orientationchange_event/index.html new file mode 100644 index 0000000000..0578edbe08 --- /dev/null +++ b/files/zh-cn/web/api/window/orientationchange_event/index.html @@ -0,0 +1,73 @@ +--- +title: orientationchange +slug: Web/API/Window/orientationchange_event +tags: + - API + - Event + - Window + - onorientationchange + - orientationchange + - 参考 + - 方向 +translation_of: Web/API/Window/orientationchange_event +--- +

orientationchange事件在设备的纵横方向改变时触发。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableNo
Interface{{domxref("Event")}}
Event handler{{domxref("Window/onorientationchange", "onorientationchange")}}
+ +

示例

+ +

你可以在{{domxref("EventTarget/addEventListener", "addEventListener")}} 方法中使用 orientationchange 事件:

+ +
window.addEventListener("orientationchange", function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+});
+
+ +

或者使用 {{domxref("Window/onorientationchange", "onorientationchange")}} 事件处理程序属性:

+ +
window.onorientationchange = function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+};
+ +

规范

+ + + + + + + + + + + + + + +
规范状态
{{SpecName('Compat', '#event-orientationchange', 'orientationchange')}}{{Spec2('Compat')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.orientationchange_event")}}

diff --git a/files/zh-cn/web/api/window/outerheight/index.html b/files/zh-cn/web/api/window/outerheight/index.html new file mode 100644 index 0000000000..9bc6b127af --- /dev/null +++ b/files/zh-cn/web/api/window/outerheight/index.html @@ -0,0 +1,77 @@ +--- +title: Window.outerHeight +slug: Web/API/Window/outerHeight +translation_of: Web/API/Window/outerHeight +--- +
+ {{APIRef}}
+

概述

+

Window.outerHeight 获取整个浏览器窗口的高度(单位:像素),包括侧边栏(如果存在)、窗口镶边(window chrome)和窗口调正边框(window resizing borders/handles)。

+

该属性为只读,没有默认值。

+

语法

+
outWindowHeight = window.outerHeight;
+
+

outWindowHeight 为窗口的外层的高度。

+

备注

+

要改变窗口的大小,请查看 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+

要获取窗口的内层高度,即页面被显示区域的高度,可查看 {{domxref("window.innerHeight")}}。

+

图像示例

+

下面的示意图展示了 outerHeightinnerHeight 两者的不同。

+

innerHeight vs outerHeight illustration

+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+

规范

+

DOM Level 0。不属于任何 W3C 技术规范或推荐。

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/outerwidth/index.html b/files/zh-cn/web/api/window/outerwidth/index.html new file mode 100644 index 0000000000..fc7a7ca3db --- /dev/null +++ b/files/zh-cn/web/api/window/outerwidth/index.html @@ -0,0 +1,71 @@ +--- +title: Window.outerWidth +slug: Web/API/Window/outerWidth +translation_of: Web/API/Window/outerWidth +--- +
+ {{APIRef}}
+

概述

+

Window.outerWidth 获取浏览器窗口外部的宽度。表示整个浏览器窗口的宽度,包括侧边栏(如果存在)、窗口镶边(window chrome)和调正窗口大小的边框(window resizing borders/handles)。

+

该属性为只读,没有默认值。

+

语法

+
outWindowWidth = window.outerWidth;
+
+

outWindowWidth 是窗口的外层的宽度。

+

备注

+

要改变一个窗口的大小,可参考 {{domxref("window.resizeBy()")}} 和 {{domxref("window.resizeTo()")}}。

+

要获取一个窗口的内层宽度(inner width),即页面被展示的区域,请参考 {{domxref("window.innerWidth")}}。

+

浏览器兼容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop(1.0)}}993
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatGeckoMobile(1.0)}}993
+
+

规范

+

DOM Level 0。不属于任何 W3C 技术规范或推荐。the To do in Notes

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/pagehide_event/index.html b/files/zh-cn/web/api/window/pagehide_event/index.html new file mode 100644 index 0000000000..a95bf134aa --- /dev/null +++ b/files/zh-cn/web/api/window/pagehide_event/index.html @@ -0,0 +1,98 @@ +--- +title: 'Window: 页面隐藏事件(pagehide event)' +slug: Web/API/Window/pagehide_event +tags: + - API + - Event + - Navigation + - pagehide event + - sendBeacon + - 前端监控 + - 埋点 + - 数据上报 +translation_of: Web/API/Window/pagehide_event +--- +
{{APIRef("HTML DOM")}}
+ +

当浏览器在显示与会话历史记录不同的页面的过程中隐藏当前页面时, pagehide(页面隐藏)事件会被发送到一个{{domxref("Window")}} 。例如,当用户单击浏览器的“后退”按钮时,当前页面在显示上一页之前会收到一个pagehide(页面隐藏)事件。

+ + + + + + + + + + + + + + + + + + + + +
Bubbles(冒泡)No
Cancelable(可取消)No
Interface(接口){{domxref("PageTransitionEvent")}}
Event handler property(事件处理程序属性){{domxref("Window.onpagehide", "onpagehide")}}
+ +

例子

+ +

在此示例中,建立了一个事件处理程序以监视 pagehide (页面隐藏)事件,并在持久保存页面以进行可能的重用时执行特殊处理。

+ +
window.addEventListener("pagehide", event => {
+  if (event.persisted) {
+    /* the page isn't being discarded, so it can be reused later */
+  }
+}, false);
+
+ +

这也可以使用 {{domxref("Window")}} 上的 {{domxref("Window.onpagehide", "onpagehide")}} 事件处理程序属性来编写:

+ +
window.onpagehide = event => {
+  if (event.persisted) {
+    /* the page isn't being discarded, so it can be reused later */
+  }
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsing-the-web.html#event-pagehide', 'pagehide')}}{{Spec2('HTML WHATWG')}}Initial specification.
{{SpecName('HTML5 W3C', 'browsers.html#event-pagehide', 'pagehide')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.pagehide_event")}}

+ +

了解更多

+ + + +
+
+
diff --git a/files/zh-cn/web/api/window/pagexoffset/index.html b/files/zh-cn/web/api/window/pagexoffset/index.html new file mode 100644 index 0000000000..d6f823e4a4 --- /dev/null +++ b/files/zh-cn/web/api/window/pagexoffset/index.html @@ -0,0 +1,92 @@ +--- +title: Window.pageXOffset +slug: Web/API/Window/pageXOffset +tags: + - API + - CSSOM +translation_of: Web/API/Window/pageXOffset +--- +
{{ APIRef() }}
+ +

这是 scrollX 的别名

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-pagexoffset', 'window.pageXOffset') }}{{ Spec2('CSSOM View') }} 
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/pageyoffset/index.html b/files/zh-cn/web/api/window/pageyoffset/index.html new file mode 100644 index 0000000000..acef4e640d --- /dev/null +++ b/files/zh-cn/web/api/window/pageyoffset/index.html @@ -0,0 +1,92 @@ +--- +title: Window.pageYOffset +slug: Web/API/Window/pageYOffset +tags: + - API + - CSSOM +translation_of: Web/API/Window/pageYOffset +--- +
{{ APIRef("CSSOM View") }}
+ +

只读属性pageYOffsetscrollY 的别名。

+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-pageyoffset', 'window.pageYOffset') }}{{ Spec2('CSSOM View') }} 
+ +

浏览器支持

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/parent/index.html b/files/zh-cn/web/api/window/parent/index.html new file mode 100644 index 0000000000..58c756ee2e --- /dev/null +++ b/files/zh-cn/web/api/window/parent/index.html @@ -0,0 +1,39 @@ +--- +title: window.parent +slug: Web/API/Window/parent +translation_of: Web/API/Window/parent +--- +

{{ ApiRef() }}

+ +

概述

+ +

返回当前窗口的父窗口对象.

+ +

如果一个窗口没有父窗口,则它的 parent 属性为自身的引用.

+ +

如果当前窗口是一个 <iframe>, <object>, 或者 <frame>,则它的父窗口是嵌入它的那个窗口

+ +

语法

+ +
var parentWindow = window.parent;
+
+ +

例子

+ +
if (window.parent != window.top) {
+  // 至少有三层窗口
+}
+
+ +

相关链接

+ + + +

规范

+ +

{{ DOM0() }}

+ +

{{ languages( { "fr": "fr/DOM/window.parent", "ja": "ja/DOM/window.parent" , "en": "en/DOM/window.parent"} ) }}

diff --git a/files/zh-cn/web/api/window/performance/index.html b/files/zh-cn/web/api/window/performance/index.html new file mode 100644 index 0000000000..926f4b6b40 --- /dev/null +++ b/files/zh-cn/web/api/window/performance/index.html @@ -0,0 +1,35 @@ +--- +title: Window.performance +slug: Web/API/Window/performance +tags: + - Window.performance + - analytics + - 前端代码埋点 +translation_of: Web/API/Window/performance +--- +
{{APIREf}}
+ +
Web Performance API允许网页访问某些函数来测量网页和Web应用程序的性能,包括 Navigation Timing API和高分辨率时间数据。
+ +

方法

+ +
+
{{domxref("Performance.mark()", "performance.mark()")}}
+
通过一个给定的名称,将该名称(作为键)和对应的{{domxref("DOMHighResTimeStamp")}}(作为值)保存在一个哈希结构里。该键值对表示了从某一时刻(译者注:某一时刻通常是 navigationStart 事件发生时刻)到记录时刻间隔的毫秒数。(译者注:该方法一般用来多次记录时间,用于求得各记录间的时间差)
+
+ +
+
{{domxref("Performance.now()", "performance.now()")}}
+
该方法返回一个{{domxref("DOMHighResTimeStamp")}}对象,该对象表示从某一时刻(译者注:某一时刻通常是 navigationStart 事件发生时刻)到调用该方法时刻的毫秒数。
+
+ +

属性

+ +
+
{{domxref("Performance.timing", "performance.timing")}}
+
是一个{{domxref("PerformanceTiming")}} 对象,包含延迟相关的性能信息。
+
{{domxref("Performance.navigation", "performance.navigation")}}
+
是一个 {{domxref("PerformanceNavigation")}} 对象,该对象表示在当前给定浏览上下文中网页导航的类型(译者注:TYPE_BACK_FORWARD,TYPE_NAVIGATE, TYPE_RELOAD,TYPE_RESERVED)以及次数。
+
performance.memory
+
在Chrome中添加的一个非标准扩展。
+
diff --git a/files/zh-cn/web/api/window/personalbar/index.html b/files/zh-cn/web/api/window/personalbar/index.html new file mode 100644 index 0000000000..e689c2cfff --- /dev/null +++ b/files/zh-cn/web/api/window/personalbar/index.html @@ -0,0 +1,73 @@ +--- +title: Window.personalbar +slug: Web/API/Window/personalbar +translation_of: Web/API/Window/personalbar +--- +
{{APIRef}}
+ +

概要

+ +

返回 personalbar 对象,其可见性可以在窗口中切换。

+ +

语法

+ +
objRef =window.personalbar
+
+ +

示例

+ +

{{todo('https://bugzilla.mozilla.org/show_bug.cgi?id=790023')}}

+ +

{{deprecated_inline}} The following complete HTML example shows the way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window. Due to deprecation of enablePrivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Various DOM Tests</title>
+
+<script>
+// changing bar states on the existing window
+netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
+window.personalbar.visible = !window.personalbar.visible;
+</script>
+
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

笔记

+ +

When you load the example page above, the browser displays the following dialog:

+ +

To toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above. Also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatically, and may affect the layout of your page.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-personalbar', 'Window.personalbar')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-personalbar', 'Window.personalbar')}}{{Spec2('HTML5 W3C')}} 
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/popstate_event/index.html b/files/zh-cn/web/api/window/popstate_event/index.html new file mode 100644 index 0000000000..ef4c63f871 --- /dev/null +++ b/files/zh-cn/web/api/window/popstate_event/index.html @@ -0,0 +1,158 @@ +--- +title: popstate +slug: Web/API/Window/popstate_event +tags: + - popstate +translation_of: Web/API/Window/popstate_event +--- +

当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。

+ +

需要注意的是调用history.pushState()history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)

+ +

不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

+ +

常规信息

+ +
+
Specification
+
HTML5
+
Interface
+
PopStateEvent
+
Bubbles
+
+
Cancelable
+
+
Target
+
defaultView
+
Default Action
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The browsing context (window).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
state {{readonlyInline}}anyThe current history entry's state object (if any).
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic supportYes{{ CompatGeckoDesktop("2") }}10.0Yeslimited
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0 (buggy in 2.2 and 2.3){{ CompatGeckoMobile("2") }}10.0Yeslimited
+
+ +

示例

+ +

 打开http://example.com/example.html页面运行以下代码, 会按预期那样打出log提示。

+ +
window.addEventListener('popstate', (event) => {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+});
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+ +

使用onpopstate事件处理程序属性的相同示例:

+ +
window.onpopstate = function(event) {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+ +

注意,虽然原始的历史项( http://example.com/example.html所对应的)没有关联的状态对象(state object),但稍后调用history.back()激活该历史项时,仍会触发popstate事件。

+ +

相关事件

+ + + +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/postmessage/index.html b/files/zh-cn/web/api/window/postmessage/index.html new file mode 100644 index 0000000000..f06a29c7de --- /dev/null +++ b/files/zh-cn/web/api/window/postmessage/index.html @@ -0,0 +1,173 @@ +--- +title: window.postMessage +slug: Web/API/Window/postMessage +tags: + - AJAX + - API + - CORS + - DOM + - Window.postMessage() + - postMessage() + - 参考 + - 方法 +translation_of: Web/API/Window/postMessage +--- +
{{ApiRef("HTML DOM")}}
+ +

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机  (两个页面的模数 {{domxref("Document.domain")}}设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

+ +

从广义上讲,一个窗口可以获得对另一个窗口的引用(比如 targetWindow = window.opener),然后在窗口上调用 targetWindow.postMessage() 方法分发一个  {{domxref("MessageEvent")}} 消息。接收消息的窗口可以根据需要自由处理此事件。传递给 window.postMessage() 的参数(比如 message )将通过消息事件对象暴露给接收消息的窗口

+ +

语法

+ +
otherWindow.postMessage(message, targetOrigin, [transfer]);
+ +
+
otherWindow
+
其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames
+
message
+
将要发送到其他 window的数据。它将会被结构化克隆算法序列化。这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化。[1]
+
targetOrigin
+
通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的origin属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是*。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。
+
transfer {{optional_Inline}}
+
是一串和message 同时传递的 {{domxref("Transferable")}} 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
+
+ +

The dispatched event

+ +

执行如下代码, 其他window可以监听分发的message:

+ +
window.addEventListener("message", receiveMessage, false);
+
+function receiveMessage(event)
+{
+  // For Chrome, the origin property is in the event.originalEvent
+  // object.
+  // 这里不准确,chrome没有这个属性
+  // var origin = event.origin || event.originalEvent.origin;
+  var origin = event.origin
+  if (origin !== "http://example.org:8080")
+    return;
+
+  // ...
+}
+
+ +

 message 的属性有:

+ +
+
data
+
从其他 window 中传递过来的对象。
+
origin
+
调用 postMessage  时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。例如 “https://example.org (隐含端口 443)”、“http://example.net (隐含端口 80)”、“http://example.com:8080”。请注意,这个origin不能保证是该窗口的当前或未来origin,因为postMessage被调用后可能被导航到不同的位置。
+
source
+
对发送消息的窗口对象的引用; 您可以使用此来在具有不同origin的两个窗口之间建立双向通信。
+
+ +
+
+ +

安全问题

+ +

如果您不希望从其他网站接收message,请不要为message事件添加任何事件侦听器。 这是一个完全万无一失的方式来避免安全问题。

+ +

如果您确实希望从其他网站接收message,请始终使用origin和source属性验证发件人的身份。 任何窗口(包括例如http://evil.example.com)都可以向任何其他窗口发送消息,并且您不能保证未知发件人不会发送恶意消息。 但是,验证身份后,您仍然应该始终验证接收到的消息的语法。 否则,您信任只发送受信任邮件的网站中的安全漏洞可能会在您的网站中打开跨网站脚本漏洞。

+ +

当您使用postMessage将数据发送到其他窗口时,始终指定精确的目标origin,而不是*。 恶意网站可以在您不知情的情况下更改窗口的位置,因此它可以拦截使用postMessage发送的数据。

+ +

示例

+ +
/*
+ * A窗口的域名是<http://example.com:8080>,以下是A窗口的script标签下的代码:
+ */
+
+var popup = window.open(...popup details...);
+
+// 如果弹出框没有被阻止且加载完成
+
+// 这行语句没有发送信息出去,即使假设当前页面没有改变location(因为targetOrigin设置不对)
+popup.postMessage("The user is 'bob' and the password is 'secret'",
+                  "https://secure.example.net");
+
+// 假设当前页面没有改变location,这条语句会成功添加message到发送队列中去(targetOrigin设置对了)
+popup.postMessage("hello there!", "http://example.org");
+
+function receiveMessage(event)
+{
+  // 我们能相信信息的发送者吗?  (也许这个发送者和我们最初打开的不是同一个页面).
+  if (event.origin !== "http://example.org")
+    return;
+
+  // event.source 是我们通过window.open打开的弹出页面 popup
+  // event.data 是 popup发送给当前页面的消息 "hi there yourself!  the secret response is: rheeeeet!"
+}
+window.addEventListener("message", receiveMessage, false);
+
+ +
/*
+ * 弹出页 popup 域名是<http://example.org>,以下是script标签中的代码:
+ */
+
+//当A页面postMessage被调用后,这个function被addEventListener调用
+function receiveMessage(event)
+{
+  // 我们能信任信息来源吗?
+  if (event.origin !== "http://example.com:8080")
+    return;
+
+  // event.source 就当前弹出页的来源页面
+  // event.data 是 "hello there!"
+
+  // 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把event.source
+  // 作为回信的对象,并且把event.origin作为targetOrigin
+  event.source.postMessage("hi there yourself!  the secret response " +
+                           "is: rheeeeet!",
+                           event.origin);
+}
+
+window.addEventListener("message", receiveMessage, false);
+
+ +

注意

+ +

任何窗口可以在任何其他窗口访问此方法,在任何时间,无论文档在窗口中的位置,向其发送消息。 因此,用于接收消息的任何事件监听器必须首先使用origin和source属性来检查消息的发送者的身份。 这不能低估:无法检查origin和source属性会导致跨站点脚本攻击。

+ +

与任何异步调度的脚本(超时,用户生成的事件)一样,postMessage的调用者不可能检测到侦听由postMessage发送的事件的事件处理程序何时抛出异常。

+ +

分派事件的origin属性的值不受调用窗口中document.domain的当前值的影响。

+ +

仅对于IDN主机名,origin属性的值不是始终为Unicode或punycode; 在使用此属性时,如果您期望来自IDN网站的消息,则最大程度地兼容性检查IDN和punycode值。 这个值最终将始终是IDN,但现在你应该同时处理IDN和punycode表单。

+ +

当发送窗口包含 javascript: 或 data: URL时,origin属性的值是加载URL的脚本的

+ +

在扩展{{Non-standard_inline}}中使用window.postMessage

+ +

window.postMessage可用于以chrome代码运行的JavaScript(例如,在扩展和特权代码中),但是分派事件的source属性总是为空作为安全限制。 (其他属性具有其期望值。)发送到位于chrome:URL的窗口的消息的targetOrigin参数当前被错误解释,使得将导致发送消息的唯一值为“*”。 由于此值是不安全的,当目标窗口可以导航到其他地方的恶意网站,建议postMessage不用于与chrome:页面的沟通; 使用不同的方法(如打开窗口时的查询字符串)与chrome窗口进行通信。 最后,在文件中向页面发布消息:URL当前要求targetOrigin参数为“*” file://不能用作安全限制; 这个限制可能会在将来被修改。

+ +

规范

+ + + + + + + + + + + + + + +
规范状态状态
{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Window.postMessage")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/print/index.html b/files/zh-cn/web/api/window/print/index.html new file mode 100644 index 0000000000..fd775a3283 --- /dev/null +++ b/files/zh-cn/web/api/window/print/index.html @@ -0,0 +1,20 @@ +--- +title: window.print +slug: Web/API/Window/print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+

概述

+

打开打印对话框打印当前文档.

+

语法

+
window.print()
+
+

规范

+

{{ DOM0() }}

+

相关链接

+
    +
  1. Printing
  2. +
  3. window.onbeforeprint
  4. +
  5. window.onafterprint
  6. +
+

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "en": "en/DOM/window.print" } ) }}

diff --git a/files/zh-cn/web/api/window/prompt/index.html b/files/zh-cn/web/api/window/prompt/index.html new file mode 100644 index 0000000000..93ce29190f --- /dev/null +++ b/files/zh-cn/web/api/window/prompt/index.html @@ -0,0 +1,54 @@ +--- +title: window.prompt +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +

{{ ApiRef() }}

+ +

概述

+ +

显示一个对话框,对话框中包含一条文字信息,用来提示用户输入文字。

+ +

语法

+ +
result = window.prompt(text, value);
+
+ + + +

例子

+ +
var sign = prompt("你是什么星座的?");
+if (sign == "天蝎座"){
+   alert("哇! 我也是天蝎座的耶!");
+}
+// 有多种使用prompt方法的方式
+var sign = window.prompt(); // 打开空的提示窗口
+var sign = prompt();       // 打开空的提示窗口
+var sign = window.prompt('觉得很幸运吗?'); // 打开显示提示文本为"觉得很幸运吗?"的提示窗口
+var sign = window.prompt('觉得很幸运吗?','是的'); // 打开显示提示文本为"觉得很幸运吗?"并且输入框默认值为"是的"的提示窗口
+
+ +

当用户点击"确定"按钮后,文本输入框中的文字被返回。如果文本输入框中为空,则返回一个空字符串。如果用户点击"取消"按钮,则返回null。

+ +

注意

+ +
一个prompt对话框,包含一个单行文本框,一个“取消”按钮,一个“确定”按钮,在对话框关闭时,返回用户输入到文本框内的值(可能为空)。
+
+prompt和alert以及类似的对话框都是模态窗口,它们会阻止用户激活程序其他部分的界面,直到该对话框关闭。因此,你不应该过度使用该方法。(译注:在content上下文,Firefox 4 以上版本使用非模态的对话框)。
+ +
Chrome上下文执行的脚本(例如扩展开发)应该使用XPCOM nsIPromptService  来替代window.prompt。
+ +

规范

+ +

{{ DOM0() }}

+ +

相关链接

+ +

alert, confirm

+ +

{{ languages( { "fr": "fr/DOM/window.prompt", "ja": "ja/DOM/window.prompt", "pl": "pl/DOM/window.prompt", "en": "en/DOM/window.prompt" } ) }}

diff --git a/files/zh-cn/web/api/window/rejectionhandled_event/index.html b/files/zh-cn/web/api/window/rejectionhandled_event/index.html new file mode 100644 index 0000000000..cf04dd5ae8 --- /dev/null +++ b/files/zh-cn/web/api/window/rejectionhandled_event/index.html @@ -0,0 +1,72 @@ +--- +title: 'Window: rejectionhandled event' +slug: Web/API/Window/rejectionhandled_event +translation_of: Web/API/Window/rejectionhandled_event +--- +
{{APIRef("HTML DOM")}}
+ +

当Promise被rejected且有rejection处理器时会在全局触发rejectionhandled 事件(通常是发生在window下,但是也可能发生在Worker中)。应用于调试一般应用回退。当Promise被rejected且没有rejection处理器处理时会触发unhandledrejection事件。这两个事件协同工作。

+ + + + + + + + + + + + + + + + + + + + +
是否冒泡No
是否可取消No
接口PromiseRejectionEvent
事件处理器属性onrejectionhandled
+ +

例子

+ +

你可以使用rejectionhandled事件在控制台打印出被rejected的Promise,以及被rejected的原因:

+ +
window.addEventListener("rejectionhandled", event => {
+  console.log("Promise rejected; reason: " + event.reason);
+}, false);
+
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#unhandled-promise-rejections', 'rejectionhandled')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.rejectionhandled_event")}}

+ +

参阅

+ + diff --git a/files/zh-cn/web/api/window/requestanimationframe/index.html b/files/zh-cn/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..b0e36717ab --- /dev/null +++ b/files/zh-cn/web/api/window/requestanimationframe/index.html @@ -0,0 +1,123 @@ +--- +title: window.requestAnimationFrame +slug: Web/API/Window/requestAnimationFrame +tags: + - API + - DOM + - DOM Reference + - Intermediate + - JavaScript timers + - Method + - NeedsBrowserCompatibility +translation_of: Web/API/window/requestAnimationFrame +--- +
{{APIRef}}
+ +

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行

+ +
注意:若你想在浏览器下次重绘之前继续更新下一帧动画,那么回调函数自身必须再次调用window.requestAnimationFrame()
+ +

当你准备更新动画时你应该调用此方法。这将使浏览器在下一次重绘之前调用你传入给该方法的动画函数(即你的回调函数)。回调函数执行次数通常是每秒60次,但在大多数遵循W3C建议的浏览器中,回调函数执行次数通常与浏览器屏幕刷新次数相匹配。为了提高性能和电池寿命,因此在大多数浏览器里,当requestAnimationFrame() 运行在后台标签页或者隐藏的{{ HTMLElement("iframe") }} 里时,requestAnimationFrame() 会被暂停调用以提升性能和电池寿命。

+ +

回调函数会被传入{{domxref("DOMHighResTimeStamp")}}参数,{{domxref("DOMHighResTimeStamp")}}指示当前被 requestAnimationFrame() 排序的回调函数被触发的时间。在同一个帧中的多个回调函数,它们每一个都会接受到一个相同的时间戳,即使在计算上一个回调函数的工作负载期间已经消耗了一些时间。该时间戳是一个十进制数,单位毫秒,最小精度为1ms(1000μs)。

+ +
+

请确保总是使用第一个参数(或其它获得当前时间的方法)计算每次调用之间的时间间隔,否则动画在高刷新率的屏幕中会运行得更快。请参考下面例子的做法。

+
+ +

语法

+ +
window.requestAnimationFrame(callback);
+
+ +

参数

+ +
+
callback
+
下一次重绘之前更新动画帧所调用的函数(即上面所说的回调函数)。该回调函数会被传入{{domxref("DOMHighResTimeStamp")}}参数,该参数与{{domxref('performance.now()')}}的返回值相同,它表示requestAnimationFrame() 开始去执行回调函数的时刻。
+
+ +

返回值

+ +

一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 {{domxref("window.cancelAnimationFrame()")}} 以取消回调函数。

+ +

范例

+ +
const element = document.getElementById('some-element-you-want-to-animate');
+let start;
+
+function step(timestamp) {
+  if (start === undefined)
+    start = timestamp;
+  const elapsed = timestamp - start;
+
+  //这里使用`Math.min()`确保元素刚好停在200px的位置。
+  element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';
+
+  if (elapsed < 2000) { // 在两秒后停止动画
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}无改变,取代旧版
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}初步定义
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.Window.requestAnimationFrame")}}

+
+ +

参阅

+ + + +
+ +
+
+
+
+ +
+ +
+
+ +
+
+
diff --git a/files/zh-cn/web/api/window/requestfilesystem/index.html b/files/zh-cn/web/api/window/requestfilesystem/index.html new file mode 100644 index 0000000000..17561dfda0 --- /dev/null +++ b/files/zh-cn/web/api/window/requestfilesystem/index.html @@ -0,0 +1,74 @@ +--- +title: Window.requestFileSystem() +slug: Web/API/Window/requestFileSystem +translation_of: Web/API/Window/requestFileSystem +--- +

{{APIRef("File System API")}}

+ +

这个非标准 {{domxref("Window")}} requestFileSystem() 方法是谷歌浏览器内核用来让web站点或app获得通过沙箱访问文件系统 . 它返回 {{domxref("FileSystem")}} 然后就可以和 file system APIs 一起使用了

+ +
+

甚至相比较如File和Directory Entries API, requestFileSystem() 更不规范; 只有Chrome支持它, 所有其它浏览器已经决定不支持它了. 它甚至已经从规范建议单中移除了. 因此不要使用这个方法

+
+ +

语法

+ +
+

在所有支持它的浏览器中这个方法都有webkit前缀 (实际上也仅有谷歌浏览器支持).

+
+ +
window.requestFileSystem(type, size, successCallback[, errorCallback]);
+ +

参数

+ +
+
type
+
要请求的存储类型. 指定Window.TEMPORARY 浏览器自行决定要不要删除文件, 例如低内存, 或者Window.PERSISTENT 如果你需要文件保持在这个地方必须用户或站点或app明确许可. 持久存储要求用户授予站点配额
+
size
+
你希望你的app被允许的使用空间大小.
+
successCallback
+
+

成功获取文件系统时调用的函数。回调接收单个参数: 一个 {{domxref("FileSystem")}} 表示应用程序有权使用的文件系统的对象.

+
+
errorCallback {{optional_inline}}
+
一个可选参数,指定在试图获取文件系统时发生错误或用户拒绝创建或访问文件系统的权限时调用的函数。回调接收单个参数作为输入:一个{{domxref("FileError")}}用来描述错误的对象
+
+ +

返回值

+ +

无返回值

+ +

示例

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

这个API没有W3C或者WHATWG的官方规范.

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.requestFileSystem")}}

+ +

相关知识

+ + diff --git a/files/zh-cn/web/api/window/requestidlecallback/index.html b/files/zh-cn/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..dc36051a1f --- /dev/null +++ b/files/zh-cn/web/api/window/requestidlecallback/index.html @@ -0,0 +1,76 @@ +--- +title: requestIdleCallback +slug: Web/API/Window/requestIdleCallback +tags: + - Idle + - requestAnimationFrame + - requestIdleCallback + - setTimeout + - 性能优化 +translation_of: Web/API/Window/requestIdleCallback +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

window.requestIdleCallback()方法将在浏览器的空闲时段内调用的函数排队。这使开发者能够在主事件循环上执行后台和低优先级工作,而不会影响延迟关键事件,如动画和输入响应。函数一般会按先进先调用的顺序执行,然而,如果回调函数指定了执行超时时间timeout,则有可能为了在超时前执行函数而打乱执行顺序。

+ +

你可以在空闲回调函数中调用requestIdleCallback(),以便在下一次通过事件循环之前调度另一个回调。

+ +
+

强烈建议使用timeout选项进行必要的工作,否则可能会在触发回调之前经过几秒钟。

+
+ +

语法

+ +
var handle = window.requestIdleCallback(callback[, options])
+ +

返回值

+ +

一个ID,可以把它传入 {{domxref("Window.cancelIdleCallback()")}} 方法来结束回调。

+ +

参数

+ +
+
callback
+
一个在事件循环空闲时即将被调用的函数的引用。函数会接收到一个名为 {{domxref("IdleDeadline")}} 的参数,这个参数可以获取当前空闲时间以及回调是否在超时时间前已经执行的状态。
+
options {{optional_inline}}
+
包括可选的配置参数。具有如下属性: +
    +
  • timeout:如果指定了timeout并具有一个正值,并且尚未通过超时毫秒数调用回调,那么回调会在下一次空闲时期被强制执行,尽管这样很可能会对性能造成负面影响。
  • +
+
+
+ +

Example

+ +

See our complete example in the article Cooperative Scheduling of Background Tasks API.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.Window.requestIdleCallback")}}

+ +

查看更多

+ + diff --git a/files/zh-cn/web/api/window/resize_event/index.html b/files/zh-cn/web/api/window/resize_event/index.html new file mode 100644 index 0000000000..bdddef32e7 --- /dev/null +++ b/files/zh-cn/web/api/window/resize_event/index.html @@ -0,0 +1,182 @@ +--- +title: resize +slug: Web/API/Window/resize_event +translation_of: Web/API/Window/resize_event +--- +

文档视图调整大小时会触发 resize 事件。

+ +

基本信息

+ +
+
规范
+
DOM L3, CSSOM View
+
接口
+
UIEvent
+
是否冒泡
+
+
是否可取消默认
+
+
事件目标
+
defaultView (window)
+
默认行为
+
None
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
+ +

案例

+ +

由于resize事件可以以较高的速率触发, 因此事件处理程序不应该执行计算开销很大的操作 (如 DOM 修改)。相反, 建议使用requestAnimationFrame, setTimeout or customEvent, 比如:

+ +

requestAnimationFrame + customEvent

+ +
;(function() {
+    var throttle = function(type, name, obj) {
+        obj = obj || window;
+        var running = false;
+        var func = function() {
+            if (running) { return; }
+            running = true;
+             requestAnimationFrame(function() {
+                obj.dispatchEvent(new CustomEvent(name));
+                running = false;
+            });
+        };
+        obj.addEventListener(type, func);
+    };
+
+    /* init - you can init any event */
+    throttle("resize", "optimizedResize");
+})();
+
+// handle event
+window.addEventListener("optimizedResize", function() {
+    console.log("Resource conscious resize callback!");
+});
+
+ +

requestAnimationFrame

+ +
var optimizedResize = (function() {
+
+    var callbacks = [],
+        running = false;
+
+    // fired on resize event
+    function resize() {
+
+        if (!running) {
+            running = true;
+
+            if (window.requestAnimationFrame) {
+                window.requestAnimationFrame(runCallbacks);
+            } else {
+                setTimeout(runCallbacks, 66);
+            }
+        }
+
+    }
+
+    // run the actual callbacks
+    function runCallbacks() {
+
+        callbacks.forEach(function(callback) {
+            callback();
+        });
+
+        running = false;
+    }
+
+    // adds callback to loop
+    function addCallback(callback) {
+
+        if (callback) {
+            callbacks.push(callback);
+        }
+
+    }
+
+    return {
+        // public method to add additional callback
+        add: function(callback) {
+            if (!callbacks.length) {
+                window.addEventListener('resize', resize);
+            }
+            addCallback(callback);
+        }
+    }
+}());
+
+// start process
+optimizedResize.add(function() {
+    console.log('Resource conscious resize callback!')
+});
+
+ +

setTimeout

+ +
(function() {
+
+  window.addEventListener("resize", resizeThrottler, false);
+
+  var resizeTimeout;
+  function resizeThrottler() {
+    // ignore resize events as long as an actualResizeHandler execution is in the queue
+    if ( !resizeTimeout ) {
+      resizeTimeout = setTimeout(function() {
+        resizeTimeout = null;
+        actualResizeHandler();
+
+       // The actualResizeHandler will execute at a rate of 15fps
+       }, 66);
+    }
+  }
+
+  function actualResizeHandler() {
+    // handle the resize event
+    ...
+  }
+
+}());
diff --git a/files/zh-cn/web/api/window/resizeby/index.html b/files/zh-cn/web/api/window/resizeby/index.html new file mode 100644 index 0000000000..ad8419af50 --- /dev/null +++ b/files/zh-cn/web/api/window/resizeby/index.html @@ -0,0 +1,43 @@ +--- +title: Window.resizeBy() +slug: Web/API/Window/resizeBy +translation_of: Web/API/Window/resizeBy +--- +
{{APIRef}}
+ +

概述

+ +

调整窗口大小。

+ +

语法

+ +
window.resizeBy(xDelta, yDelta)
+
+ +

参数

+ + + +

例子

+ +
// 缩小窗口
+window.resizeBy(-200, -200);
+
+ +

备注

+ +

该方法相对于窗口当前大小来调整该窗口的大小。要以绝对大小方式调整窗口的大小,可使用 {{domxref("window.resizeTo")}}。

+ +

从 Firefox 7,依据下面的规则,不能再调整浏览器内一个窗口的默认大小了:

+ +
    +
  1. 不能调整非 window.open 方法打开的窗口或 Tab 的大小。
  2. +
  3. 当一个窗口内包含有一个以上的 Tab 时,不能调整窗口的大小。
  4. +
+ +

规范

+ +

DOM Level 0。不属于规范。

diff --git a/files/zh-cn/web/api/window/resizeto/index.html b/files/zh-cn/web/api/window/resizeto/index.html new file mode 100644 index 0000000000..96fc9833ed --- /dev/null +++ b/files/zh-cn/web/api/window/resizeto/index.html @@ -0,0 +1,34 @@ +--- +title: Window.resizeTo +slug: Web/API/Window/resizeTo +translation_of: Web/API/Window/resizeTo +--- +
+ {{APIRef}}
+

概述

+

动态调整窗口的大小。

+

语法

+
window.resizeTo(aWidth, aHeight)
+
+

参数

+ +

示例

+
// 将窗口设置为整个屏幕的 1/4 大小(面积)
+function quarter() {
+  window.resizeTo(
+    window.screen.availWidth / 2,
+    window.screen.availHeight / 2
+  );
+}
+

备注

+

从 Firefox 7 开始,不能改变浏览器窗口的大小了,要依据下面的规则

+
    +
  1. 不能设置那些不是通过 window.open 创建的窗口或 Tab 的大小。
  2. +
  3. 当一个窗口里面含有一个以上的 Tab 时,无法设置窗口的大小。
  4. +
+

相关链接 {{domxref("window.resizeBy")}}.

+

规范

+

{{dom0}}

diff --git a/files/zh-cn/web/api/window/restore/index.html b/files/zh-cn/web/api/window/restore/index.html new file mode 100644 index 0000000000..bc704660b6 --- /dev/null +++ b/files/zh-cn/web/api/window/restore/index.html @@ -0,0 +1,16 @@ +--- +title: Window.restore() +slug: Web/API/Window/restore +translation_of: Web/API/Window/moveTo +--- +

{{APIRef}}

+ +

这个方法现在已经失效,不过可以使用下面的方法代替:

+ +

{{domxref("window.moveTo")}}({{domxref("window.screenX")}}, {{domxref("window.screenY")}});

+ +

Browser Compatibility

+ + + +

{{Compat("api.Window.restore")}}

diff --git a/files/zh-cn/web/api/window/screen/index.html b/files/zh-cn/web/api/window/screen/index.html new file mode 100644 index 0000000000..699d85d5c7 --- /dev/null +++ b/files/zh-cn/web/api/window/screen/index.html @@ -0,0 +1,32 @@ +--- +title: Window.screen +slug: Web/API/Window/screen +tags: + - screen +translation_of: Web/API/Window/screen +--- +
{{APIRef("CSSOM View")}}
+ +

返回当前window的screen对象。screen对象实现了{{domxref("Screen")}}接口,它是个特殊的对象,返回当前渲染窗口中和屏幕有关的属性。

+ +

语法

+ +
screenObj = window.screen;
+
+ +

 

+ +

示例

+ +

 

+ +
if (screen.pixelDepth < 8) {
+  // use low-color version of page
+} else {
+  // use regular, colorful page
+}
+
+ +

Specification

+ +

TBD

diff --git a/files/zh-cn/web/api/window/screenleft/index.html b/files/zh-cn/web/api/window/screenleft/index.html new file mode 100644 index 0000000000..a3a64a5164 --- /dev/null +++ b/files/zh-cn/web/api/window/screenleft/index.html @@ -0,0 +1,88 @@ +--- +title: Window.screenLeft +slug: Web/API/Window/screenLeft +translation_of: Web/API/Window/screenLeft +--- +
{{APIRef}}
+ +

Window.screenLeft 是一个只读属性,它返回浏览器左边框到左边屏幕边缘的 CSS 像素数。

+ +
+

注意screenLeft 只是 {{domxref("Window.screenX")}}  属性的别名,最初只被 IE 浏览器所支持。现在主流的浏览器都已支持该属性。

+
+ +

语法

+ +
leftWindowPos = window.screenLeft
+
+ +

返回值

+ +

返回浏览器窗口到屏幕左边缘的 CSS 像素距离数值。

+ +

例子

+ +

在 screenleft-screentop 项目中,展示了一个监听浏览器窗口位置变化,动态更新 canvas 的例子。在这个例子中,当你移动浏览器窗口位置,绘制在 canvas 上的圆也会对应移动。我们通过监听 screenLeft/screenTop 的变化,并使用 {{domxref("Window.requestAnimationFrame()")}} 来对 canvas 实时重绘,保证了浏览器窗口移动时,canvas 内部圆的位置也会发生对应的移动。

+ +
initialLeft = window.screenLeft + canvasElem.offsetLeft;
+initialTop = window.screenTop + canvasElem.offsetTop;
+
+function positionElem() {
+  let newLeft = window.screenLeft + canvasElem.offsetLeft;
+  let newTop = window.screenTop + canvasElem.offsetTop;
+
+  let leftUpdate = initialLeft - newLeft;
+  let topUpdate = initialTop - newTop;
+
+  ctx.fillStyle = 'rgb(0, 0, 0)';
+  ctx.fillRect(0, 0, width, height);
+  ctx.fillStyle = 'rgb(0, 0, 255)';
+  ctx.beginPath();
+  ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false);
+  ctx.fill();
+
+  pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop;
+
+  window.requestAnimationFrame(positionElem);
+}
+
+window.requestAnimationFrame(positionElem);
+ +

如果浏览器不支持 screenLeft属性,我们还在代码中使用了一个 polyfill 来保证演示效果。通过设置 {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}} 为对应别名来实现一样的功能。

+ +
if(!window.screenLeft) {
+  window.screenLeft = window.screenX;
+  window.screenTop = window.screenY;
+}
+ +

说明

+ + + + + + + + + + + + + + + + +
规范状态提交
{{ SpecName('CSSOM View', '#dom-window-screenx', 'Window.screenLeft') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.screenLeft")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/screentop/index.html b/files/zh-cn/web/api/window/screentop/index.html new file mode 100644 index 0000000000..35067bb48d --- /dev/null +++ b/files/zh-cn/web/api/window/screentop/index.html @@ -0,0 +1,88 @@ +--- +title: Window.screenTop +slug: Web/API/Window/screenTop +translation_of: Web/API/Window/screenTop +--- +

{{APIRef}}

+ +

Window.screenTop 只读属性返回垂直距离,单位是CSS 像素, 从用户浏览器的上边界到屏幕最顶端。

+ +
+

Note: screenTop is an alias of the older {{domxref("Window.screenY")}} property. screenTop was originally supported only in IE but was introduced everywhere due to popularity.

+
+ +

语法

+ +
topWindowPos = window.screenTop
+
+ +

返回值

+ +

A number equal to the number of CSS pixels from the top edge of the browser viewport to the  top edge of the screen.

+ +

例子

+ +

In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus {{domxref("Window.requestAnimationFrame()")}} to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.

+ +
initialLeft = window.screenLeft + canvasElem.offsetLeft;
+initialTop = window.screenTop + canvasElem.offsetTop;
+
+function positionElem() {
+  let newLeft = window.screenLeft + canvasElem.offsetLeft;
+  let newTop = window.screenTop + canvasElem.offsetTop;
+
+  let leftUpdate = initialLeft - newLeft;
+  let topUpdate = initialTop - newTop;
+
+  ctx.fillStyle = 'rgb(0, 0, 0)';
+  ctx.fillRect(0, 0, width, height);
+  ctx.fillStyle = 'rgb(0, 0, 255)';
+  ctx.beginPath();
+  ctx.arc(leftUpdate + (width/2), topUpdate + (height/2) + 35, 50, degToRad(0), degToRad(360), false);
+  ctx.fill();
+
+  pElem.textContent = 'Window.screenLeft: ' + window.screenLeft + ', Window.screenTop: ' + window.screenTop;
+
+  window.requestAnimationFrame(positionElem);
+}
+
+window.requestAnimationFrame(positionElem);
+ +

Also in the code we include a snippet that detects whether screenLeft is supported, and if not, polyfills in screenLeft/screenTop using {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}}.

+ +
if(!window.screenLeft) {
+  window.screenLeft = window.screenX;
+  window.screenTop = window.screenY;
+}
+ +

说明

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-screeny', 'Window.screenTop') }}{{ Spec2('CSSOM View') }}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.screenTop")}}

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/screenx/index.html b/files/zh-cn/web/api/window/screenx/index.html new file mode 100644 index 0000000000..44048dfe03 --- /dev/null +++ b/files/zh-cn/web/api/window/screenx/index.html @@ -0,0 +1,21 @@ +--- +title: Window.screenX +slug: Web/API/Window/screenX +translation_of: Web/API/Window/screenX +--- +
+ {{APIRef}}
+

概述

+

返回浏览器左边界到操作系统桌面左边界的水平距离。

+

语法

+
lLoc = window.screenX
+
+ +

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/screeny/index.html b/files/zh-cn/web/api/window/screeny/index.html new file mode 100644 index 0000000000..23f2fcdb2a --- /dev/null +++ b/files/zh-cn/web/api/window/screeny/index.html @@ -0,0 +1,21 @@ +--- +title: Window.screenY +slug: Web/API/Window/screenY +translation_of: Web/API/Window/screenY +--- +
+ {{APIRef}}
+

概述

+

返回浏览器顶部距离系统桌面顶部的垂直距离。

+

语法

+
lLoc = window.screenY
+
+ +

规范

+

{{dom0}}

+

相关链接

+ diff --git a/files/zh-cn/web/api/window/scroll/index.html b/files/zh-cn/web/api/window/scroll/index.html new file mode 100644 index 0000000000..dd889bbe60 --- /dev/null +++ b/files/zh-cn/web/api/window/scroll/index.html @@ -0,0 +1,70 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +tags: + - 全局方法 +translation_of: Web/API/Window/scroll +--- +
{{APIRef}}
+ +

概述

+ +

滚动窗口至文档中的特定位置。

+ +

语法

+ +
window.scroll(x-coord, y-coord)
+window.scroll(options)
+
+ +

参数

+ + + +

- 或者 -

+ + + +

示例

+ +
<!-- 把纵轴上第 100 个像素置于窗口顶部 -->
+
+<button onClick="scroll(0, 100);">点击以向下滚动 100 像素</button>
+
+ +

使用 options:

+ +
window.scroll({
+  top: 100,
+  left: 100,
+  behavior: 'smooth'
+});
+
+ +

备注

+ +

window.scrollTo 实际上和该方法是相同的。想要重复地滚动某个距离,请使用 window.scrollBy. 参见 window.scrollByLines, window.scrollByPages.

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{ SpecName('CSSOM View', '#dom-window-scrollto', 'window.scrollTo()') }}{{ Spec2('CSSOM View') }}初始定义
diff --git a/files/zh-cn/web/api/window/scrollbars/index.html b/files/zh-cn/web/api/window/scrollbars/index.html new file mode 100644 index 0000000000..6afc2a7ddd --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbars/index.html @@ -0,0 +1,65 @@ +--- +title: Window.scrollbars +slug: Web/API/Window/scrollbars +translation_of: Web/API/Window/scrollbars +--- +

{{ APIRef() }}

+ +

概要

+ +

返回可以检查其可见性的滚动条对象。

+ +

语法

+ +
objRef = window.scrollbars
+
+ +

示例

+ +

下面的HTML示例展示了如何使用window.scrollbars对象的visible 属性。

+ +
<!doctype html>
+<html>
+<head>
+  <title>Various DOM Tests</title>
+  <script>
+    var visibleScrollbars = window.scrollbars.visible;
+  </script>
+</head>
+<body>
+  <p>Various DOM Tests</p>
+</body>
+</html>
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-window-scrollbars', 'Window.scrollbars')}}现行标准 
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-scrollbars', 'Window.scrollbars')}}官方推荐 
+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/scrollby/index.html b/files/zh-cn/web/api/window/scrollby/index.html new file mode 100644 index 0000000000..fea5cc42e3 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollby/index.html @@ -0,0 +1,84 @@ +--- +title: Window.scrollBy() +slug: Web/API/Window/scrollBy +tags: + - 全局方法 +translation_of: Web/API/Window/scrollBy +--- +

{{ APIRef() }}

+ +

摘要

+ +

在窗口中按指定的偏移量滚动文档。

+ +

语法

+ +
window.scrollBy(x-coord, y-coord);
+window.scrollBy(options)
+
+ +

参数

+ + + +

正数坐标会朝页面的右下方滚动,负数坐标会滚向页面的左上方。

+ + + +
    +
  1. top 等同于  y-coord
  2. +
  3. left 等同于  x-coord
  4. +
  5. behavior  表示滚动行为,支持参数:smooth (平滑滚动),instant (瞬间滚动),默认值 auto,效果等同于 instant
  6. +
+ +

例子

+ +

向下滚动一页:

+ +
window.scrollBy(0, window.innerHeight);
+
+ + + +

向上滚动一页:

+ +
window.scrollBy(0, -window.innerHeight);
+ + + +

使用 options:

+ +
window.scrollBy({
+  top: 100,
+  left: 100,
+  behavior: "smooth"
+});
+
+ +

注意

+ +

window.scrollBy 滚动指定的距离,而 window.scroll 滚动至文档中的绝对位置。另外还有 window.scrollByLines, window.scrollByPages

+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态说明
{{ SpecName('CSSOM View', '#dom-window-scrollby', 'window.scrollBy()') }}{{ Spec2('CSSOM View') }}初次定义
diff --git a/files/zh-cn/web/api/window/scrollbylines/index.html b/files/zh-cn/web/api/window/scrollbylines/index.html new file mode 100644 index 0000000000..d11f31562c --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbylines/index.html @@ -0,0 +1,56 @@ +--- +title: Window.scrollByLines() +slug: Web/API/Window/scrollByLines +tags: + - API + - DOM + - Method + - Non-standard + - Window + - 方法 + - 非标准 +translation_of: Web/API/Window/scrollByLines +--- +

 

+ +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +

概要

+ +

按给定的行数滚动文档。

+ +

语法

+ +
window.scrollByLines(lines)
+
+ +

参数

+ + + +

例子

+ +
<!-- 向下滚动5行。 -->
+<button onclick="scrollByLines(5);">down 5 lines</button>
+
+ +
<!-- 向上滚动5行。 -->
+<button onclick="scrollByLines(-5);">up 5 lines</button>
+
+ +

规范

+ +

这不是任何规范的一部分。

+ +

参考

+ + diff --git a/files/zh-cn/web/api/window/scrollbypages/index.html b/files/zh-cn/web/api/window/scrollbypages/index.html new file mode 100644 index 0000000000..f2618eca98 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollbypages/index.html @@ -0,0 +1,40 @@ +--- +title: window.scrollByPages +slug: Web/API/Window/scrollByPages +translation_of: Web/API/Window/scrollByPages +--- +

{{ ApiRef() }}

+ +

概述

+ +

在当前文档页面按照指定的页数翻页.

+ +

语法

+ +
window.scrollByPages(pages)
+
+ +

参数

+ + + +

例子

+ +
// 当前文档向下翻一页
+window.scrollByPages(1);
+
+// 当前文档向上翻一页
+window.scrollByPages(-1);
+
+ +

备注

+ +

查看 window.scrollBy, window.scrollByLines, window.scroll, window.scrollTo.

+ +

规范

+ +

DOM Level 0 不属于任何标准

+ +

{{ languages( { "ja": "ja/DOM/window.scrollByPages", "pl": "pl/DOM/window.scrollByPages", "en": "en/DOM/window.scrollByPages" } ) }}

diff --git a/files/zh-cn/web/api/window/scrollmaxx/index.html b/files/zh-cn/web/api/window/scrollmaxx/index.html new file mode 100644 index 0000000000..c6cebd7d02 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollmaxx/index.html @@ -0,0 +1,45 @@ +--- +title: Window.scrollMaxX +slug: Web/API/Window/scrollMaxX +tags: + - API + - DOM + - Window + - 属性 + - 接口 +translation_of: Web/API/Window/scrollMaxX +--- +
{{APIRef}} {{Non-standard_header}}
+ +

Window.scrollMaxX 只读属性,返回有关文档可水平滚动的最大像素数。

+ +

语法

+ +
xMax = window.scrollMaxX
+
+ + + +

示例

+ +
// 滚动到页面的右边缘
+let maxX = window.scrollMaxX;
+
+window.scrollTo(maxX, 0);
+
+ +

提示

+ +

不要用这个属性来获得文档总宽度,文档总宽度不等于window.innerWidth + window.scrollMaxX。因为 {{domxref("window.innerWidth")}}包含所有可见的垂直滚动条的宽度,所以结果会超出文档总宽度,多出所有可见的垂直滚动条的宽度。作为替代,可使用{{domxref("element.scrollWidth","document.body.scrollWidth")}}。查看相关:{{domxref("window.scrollMaxY")}}。

+ +

规范

+ +

不属于任何规范。

+ +

浏览器兼容

+ + + +

{{Compat("api.Window.scrollMaxX")}}

diff --git a/files/zh-cn/web/api/window/scrollmaxy/index.html b/files/zh-cn/web/api/window/scrollmaxy/index.html new file mode 100644 index 0000000000..3012d9d244 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollmaxy/index.html @@ -0,0 +1,48 @@ +--- +title: Window.scrollMaxY +slug: Web/API/Window/scrollMaxY +tags: + - API + - DOM_0 + - HTML DOM + - 参考 + - 属性 + - 非标准 +translation_of: Web/API/Window/scrollMaxY +--- +
{{APIRef}} {{Non-standard_header}}
+ +

只读属性Window.scrollMaxY返回document可以纵向滚动的最大像素数目

+ +

语法

+ +
yMax = window.scrollMaxY
+
+ + + +

例子

+ +
// 滚动到页面的底部
+let maxY = window.scrollMaxY;
+
+window.scrollTo(0, maxY);
+
+ +

备注

+ +

不要用 {{domxref("window.innerHeight")}} + window.scrollMaxY 来计算document的总高度,因为 {{domxref("window.innerHeight")}} 也包括了可见的水平滚动条的高度。正确的做法是使用 {{domxref("element.scrollHeight","document.body.scrollHeight")}} 。

+ +

参见{{domxref("window.scrollMaxX")}} 和 {{domxref("window.scrollTo")}} 。

+ +

规范

+ +

这不属于任何规范中的一部分。

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.scrollMaxY")}}

diff --git a/files/zh-cn/web/api/window/scrollto/index.html b/files/zh-cn/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..715e3f0190 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollto/index.html @@ -0,0 +1,58 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

摘要

+ +

滚动到文档中的某个坐标。

+ +

语法

+ +
window.scrollTo(x-coord,y-coord )
+
+window.scrollTo(options)
+ +

参数

+ + + +
    +
  1. top 等同于  y-coord
  2. +
  3. left 等同于  x-coord
  4. +
  5. behavior  类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant
  6. +
+ +
+
+ +

例子

+ +
window.scrollTo( 0, 1000 );
+
+// 设置滚动行为改为平滑的滚动
+window.scrollTo({
+    top: 1000,
+    behavior: "smooth"
+});
+
+ +

注意

+ +

该函数实际上和 window.scroll是一样的。 相对滚动可以参考 window.scrollBywindow.scrollByLines,和 window.scrollByPages

+ +

规范

+ +

{{dom0}}

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.scrollTo")}}

diff --git a/files/zh-cn/web/api/window/scrollx/index.html b/files/zh-cn/web/api/window/scrollx/index.html new file mode 100644 index 0000000000..8981bee856 --- /dev/null +++ b/files/zh-cn/web/api/window/scrollx/index.html @@ -0,0 +1,34 @@ +--- +title: Window.scrollX +slug: Web/API/Window/scrollX +translation_of: Web/API/Window/scrollX +--- +
+ {{ APIRef() }}
+

概述

+

返回文档/页面水平方向滚动的像素值。

+

语法

+
var x = window.scrollX;
+

参数

+ +

示例

+
// 如果 scrollX 大于 400,则把文档重新滚动到左上角。
+if (window.scrollX > 400) {
+  window.scroll(0,0);
+}
+

备注

+

pageXOffset 属性是 scrollX 属性的别名:

+
window.pageXOffset == window.scrollX; // 总是 true
+

为了跨浏览器兼容性,请使用 window.pageXOffset 代替 window.scrollX。另外,旧版本的 IE(<9)两个属性都不支持,必须通过其他的非标准属性来解决此问题。完整的兼容性代码如下:

+
var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
+var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
+

规范

+ +

相关链接

+ diff --git a/files/zh-cn/web/api/window/scrolly/index.html b/files/zh-cn/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..7bc49120f2 --- /dev/null +++ b/files/zh-cn/web/api/window/scrolly/index.html @@ -0,0 +1,131 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +tags: + - API + - Reference + - 参考 + - 属性 +translation_of: Web/API/Window/scrollY +--- +
{{APIRef}}
+ +

概述

+ +

返回文档在垂直方向已滚动的像素值。

+ +

语法

+ +
var y = window.scrollY;
+ + + +

示例

+ +
// 保证刚好滚动到第二页
+if (window.scrollY) {
+  window.scroll(0, 0);  // 重置滚动位置为文档的左上角
+}
+
+window.scrollByPages(1);
+ +

备注

+ +

如果正在使用相对滚动函数,如 {{domxref("window.scrollBy")}}、{{domxref("window.scrollByLines")}} 或 {{domxref("window.scrollByPages")}},则需要使用该属性来检测文档是否已被滚动了某段距离。

+ +

pageYOffset 属性是 scrollY 属性的别名:

+ +
window.pageYOffset == window.scrollY; // 总是返回 true
+ +

为了跨浏览器兼容,请使用 window.pageYOffset 代替 window.scrollY。另外,旧版本IE(<9)两个属性都不支持,必须使用其他的非标准属性。完整的兼容性代码如下:

+ +
var supportPageOffset = window.pageXOffset !== undefined;
+var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
+
+var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
+var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrolly', 'window.scrollY') }}{{ Spec2('CSSOM View') }} 
+ +
+

Browser compatibility

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/self/index.html b/files/zh-cn/web/api/window/self/index.html new file mode 100644 index 0000000000..2d0504ef26 --- /dev/null +++ b/files/zh-cn/web/api/window/self/index.html @@ -0,0 +1,22 @@ +--- +title: Window.self +slug: Web/API/Window/self +translation_of: Web/API/Window/self +--- +

{{ APIRef() }}

+

概述

+

返回一个指向当前 window 对象的引用。

+

语法

+
objRef = window.self
+
+

示例

+
 if (window.parent.frames[0] != window.self) {
+    // 当前对象不是frames列表中的第一个时
+ }
+
+

备注

+

window.self 几乎总是用于上面示例那样的比较,用来判断当前 window 是不是父 frameset 中的第一个 frame。

+

规范

+

HTML5

+
+  
diff --git a/files/zh-cn/web/api/window/sessionstorage/index.html b/files/zh-cn/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..d11bc0497a --- /dev/null +++ b/files/zh-cn/web/api/window/sessionstorage/index.html @@ -0,0 +1,113 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - API + - Web Storage + - WindowSessionStorage + - sessionStorage + - 存储 + - 属性 +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

sessionStorage 属性允许你访问一个,对应当前源的 session {{domxref("Storage")}} 对象。它与 {{domxref("Window.localStorage", "localStorage")}} 相似,不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。

+ + + +
+

应该注意,存储在sessionStorage或localStorage中的数据特定于页面的协议。也就
+ 是说http://example.comhttps://example.com的sessionStorage相互隔离。

+ +

被存储的键值对总是以UTF-16 DOMString 的格式所存储,其使用两个字节来表示一个字符。对于对象、整数key值会自动转换成字符串形式。

+
+ +

语法

+ +
// 保存数据到 sessionStorage
+sessionStorage.setItem('key', 'value');
+
+// 从 sessionStorage 获取数据
+let data = sessionStorage.getItem('key');
+
+// 从 sessionStorage 删除保存的数据
+sessionStorage.removeItem('key');
+
+// 从 sessionStorage 删除所有保存的数据
+sessionStorage.clear();
+
+
+ +

返回值

+ +

一个 {{domxref("Storage")}} 对象。

+ +

示例

+ +

下面的代码访问当前域名的 session {{domxref("Storage")}} 对象,并使用 {{domxref("Storage.setItem()")}} 访问往里面添加一个数据条目。

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

下面的示例会自动保存一个文本输入框的内容,如果浏览器因偶然因素被刷新了,文本输入框里面的内容会被恢复,因此写入的内容不会丢失。

+ +
// 获取文本输入框
+let field = document.getElementById("field");
+
+// 检测是否存在 autosave 键值
+// (这个会在页面偶然被刷新的情况下存在)
+if (sessionStorage.getItem("autosave")) {
+  // 恢复文本输入框的内容
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// 监听文本输入框的 change 事件
+field.addEventListener("change", function() {
+  // 保存结果到 sessionStorage 对象中
+  sessionStorage.setItem("autosave", field.value);
+});
+
+ +
+

备注:完整的使用示例可以查看使用 Web Storage API一文。

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}{{Spec2('Web Storage')}}
+ +

浏览器兼容性

+ +

{{Compat("api.Window.sessionStorage")}}
+ 各浏览器支持的 localStorage 和 sessionStorage 容量上限不同。测试页面 detailed rundown of all the storage capacities for various browsers

+ +
+ +
+

Note: 从iOS 5.1之后,移动端的Safari将localStorage数据存储在cache文件中,在操作系统的要求下,会偶尔进行清除,特别是空间不足时。

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/window/setcursor/index.html b/files/zh-cn/web/api/window/setcursor/index.html new file mode 100644 index 0000000000..d87850c4d3 --- /dev/null +++ b/files/zh-cn/web/api/window/setcursor/index.html @@ -0,0 +1,32 @@ +--- +title: Window.setCursor() +slug: Web/API/Window/setCursor +translation_of: Web/API/Window/setCursor +--- +
{{ ApiRef() }}
+ +
+

{{Non-standard_header}}

+
+ +
 
+ +

概要

+ +

在当前窗口中改变光标(鼠标)的样子

+ +

例子

+ +
function setBusyCursor(enable) {
+  window.setCursor(enable ? "wait" : "auto");
+}
+ +

提示

+ +

鼠标样式不会自动重置,需要主动设置回 auto 属性。

+ +

这个函数方法是 ChromeWindow interface 的一部分. 这个方法在某些网页上不能用, 可以使用 CSS {{cssxref("cursor")}} 代替.

+ +

规范

+ +

这不是任何规范的一部分

diff --git a/files/zh-cn/web/api/window/setimmediate/index.html b/files/zh-cn/web/api/window/setimmediate/index.html new file mode 100644 index 0000000000..12016988ac --- /dev/null +++ b/files/zh-cn/web/api/window/setimmediate/index.html @@ -0,0 +1,54 @@ +--- +title: window.setImmediate +slug: Web/API/Window/setImmediate +tags: + - DOM + - setImmediate +translation_of: Web/API/Window/setImmediate +--- +

{{APIRef("HTML DOM")}}{{Non-standard_header}}

+ +

该方法用来把一些需要长时间运行的操作放在一个回调函数里,在浏览器完成后面的其他语句后,就立刻执行这个回调函数。

+ +
注意: 该方法可能不会被批准成为标准,目前只有最新版本的 Internet Explorer 和Node.js 0.10+实现了该方法。它遇到了 Gecko(Firefox) 和Webkit (Google/Apple) 的阻力.
+ +

语法

+ +
var immediateID = setImmediate(func, [param1, param2, ...]);
+var immediateID = setImmediate(func);
+
+ + + +

所有参数都会直接传给你的函数。

+ +

备注

+ +

{{ domxref("window.clearImmediate") }} 方法可以用来取消通过setImmediate设置的将要执行的语句, 就像 {{ domxref("window.clearTimeout") }} 对应于 {{ domxref("window.setTimeout") }}一样.

+ +

该方法可以用来替代 setTimeout(fn, 0) 去执行繁重的操作(heavy operations

+ +

可以通过以下几种方式来模仿该功能:

+ + + +

所有这些技术都被纳入 robust setImmediate polyfill 中.

+ +

浏览器兼容性

+ +

{{Compat("api.Window.setImmediate")}}

+ +

相关链接

+ +

{{ domxref("window.clearImmediate") }}

+ +

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

+ +

Microsoft setImmediate API Demo

diff --git a/files/zh-cn/web/api/window/setinterval/index.html b/files/zh-cn/web/api/window/setinterval/index.html new file mode 100644 index 0000000000..385a19b81b --- /dev/null +++ b/files/zh-cn/web/api/window/setinterval/index.html @@ -0,0 +1,635 @@ +--- +title: window.setInterval +slug: Web/API/Window/setInterval +tags: + - API + - DOM + - 定时 + - 方法 + - 时间 +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} 的 setInterval() 方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

+ +

在窗口和工作接口上提供的setInterval()方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个时间间隔ID,该ID唯一地标识时间间隔,因此您可以稍后通过调用clearInterval()来删除它。这个方法是由WindowOrWorkerGlobalScope mixin定义的。

+ +

语法

+ +
var intervalID = scope.setInterval(func, delay, [arg1, arg2, ...]);
+var intervalID = scope.setInterval(code, delay);
+
+ +

参数

+ +
+
func
+
要重复调用的函数。 每经过指定 延迟 毫秒后执行的{{jsxref("函数")}} 。该函数不接受任何参数,也没有返回值。
+
code
+
这个语法是可选的,你可以传递一个字符串来代替一个函数对象,你传递的字符串会被编译然后每个delay毫秒时间内执行一次。这个语法因为存在安全风险所以不被推荐使用。
+
delay
+
是每次延迟的毫秒数 (一秒等于1000毫秒),函数的每次调用会在该延迟之后发生。和setTimeout一样,实际的延迟时间可能会稍长一点。这个时间计算单位是毫秒(千分之一秒),这个定时器会使指定方法或者代码段执行的时候进行时间延迟。如果这个参数值小于10,则默认使用值为10。请注意,真正延迟时间或许更长; 请参考示例: {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} 
+
arg1, ..., argN {{optional_inline}}
+
当定时器过期的时候,将被传递给func指定函数的附加参数。
+
+ +

返回值

+ +

此返回值intervalID是一个非零数值,用来标识通过setInterval()创建的计时器,这个值可以用来作为clearInterval()的参数来清除对应的计时器 。

+ +

值得注意的是,setInterval()setTimeout()共享同一个ID池,并且clearInterval()clearTimeout()在技术上是可互换使用的。但是,我们必须去匹配clearInterval()clearTimeout()对应的id,以避免代码杂乱无章,增强代码的可维护性。

+ +
Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
+ +

示例

+ +

例1:基本用法

+ +

下面例子是 setInterval()的基本语法

+ +
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);
+}
+
+ +

例2:两种颜色的切换

+ +

下面的例子里会每隔一秒就调用函数 flashtext() 一次,直至你通过按下 Stop 按钮来清除本次重复操作的唯一辨识符 intervalID

+ +
<!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>
+
+ +

例3:打字机效果

+ +

下面这个例子通过键入、删除和再次键入所有 NodeList 中的符合特定的选择器的字符,以达到打字机的效果。

+ +
+
<!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>
+
+ +

查看示例效果,亦可参考:clearInterval()

+ +

回调参数

+ +

如前所述,Internet Explorer 9及以下版本不支持在setTimeout()setInterval()中向回调函数传递参数。下面的IE专用代码演示了一种克服这种限制的方法。使用时,只需将以下代码添加到你的脚本顶部即可。

+ +
/*\
+|*|
+|*|  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;
+}
+
+ +

另一种方式是使用匿名函数调用你的回调函数,但是这种方式开销较大。例如:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

还有一种方式是使用 function's bind. 例如:

+ +
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
+ +

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

+ +

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

+ +

"this" 的问题

+ +

当你给 setInterval() 传递一个方法或者函数的时候,this 值的绑定会存在一些问题。  这个问题在JavaScript 参考 进行了详细解释。

+ +

解释

+ +

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

+ +
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
+
+ +

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

+ +

一个可能的解决方案

+ +

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

+ +
// 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);
+};
+ +
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 non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
+ +

New feature test:

+ +
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
+
+ +

Another, more complex, solution for the this problem is the following framework.

+ +
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this 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 arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
+ +

MiniDaemon:一个用于管理定时器的小框架

+ +

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 this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

+ +
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
+ +

minidaemon.js

+ +
+
/*\
+|*|
+|*|  :: 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();
+};
+
+
+ +
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.
+ +

语法

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

说明

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

参数

+ +
+
thisObject
+
The this object on which the callback function is called. It can be an object or null.
+
callback
+
The function that is repeatedly invoked . It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
+
rate (optional)
+
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
+
length (optional)
+
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
+
+ +

MiniDaemon 实例(instance)的属性

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
The time lapse (in number of milliseconds) between each invocation (read/write).
+
myDaemon.length
+
The total number of invocations. It can be a positive integer or Infinity (read/write).
+
+ +

MiniDaemon 实例的方法

+ +
+
myDaemon.isAtEnd()
+
Returns a boolean expressing whether the daemon is at the start/end position or not.
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon 全局对象的方法

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
+
+ +

使用示例

+ +

HTML:

+ +
<!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>
+ +

View this example in action

+ +

备注

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

+ +

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

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 setInterval 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.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() 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.

+ +

Throttling of intervals

+ +

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/window/settimeout/index.html b/files/zh-cn/web/api/window/settimeout/index.html new file mode 100644 index 0000000000..f9813851f7 --- /dev/null +++ b/files/zh-cn/web/api/window/settimeout/index.html @@ -0,0 +1,476 @@ +--- +title: window.setTimeout +slug: Web/API/Window/setTimeout +tags: + - Timers + - WindowOrWorkerGlobalScope + - WindowTimers + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +

{{APIRef("HTML DOM")}}

+ +

 {{domxref("WindowOrWorkerGlobalScope")}} 混合的 setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

+ +

语法

+ +
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
+var timeoutID = scope.setTimeout(function[, delay]);
+var timeoutID = scope.setTimeout(code[, delay]);
+ +

参数

+ +
+
function
+
{{jsxref("function")}} 是你想要在到期时间(delay毫秒)之后执行的函数
+
code
+
这是一个可选语法,你可以使用字符串而不是{{jsxref("function")}} ,在delay毫秒之后编译和执行字符串 (使用该语法是不推荐的, 原因和使用 {{jsxref("Global_Objects/eval", "eval()")}}一样,有安全风险)。
+
delay {{optional_inline}}
+
延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,原因请查看{{anch("实际延时比设定值更久的原因:最小延迟时间")}}。
+
arg1, ..., argN {{optional_inline}}
+
附加参数,一旦定时器到期,它们会作为参数传递给{{jsxref("function")}} 
+
+ +
+

备注:需要注意的是,IE9 及更早的 IE 浏览器不支持向回调函数传递额外参数(第一种语法)。如果你想要在IE中达到同样的功能,你必须使用一种兼容代码 (查看  {{anch("兼容旧环境(polyfill)")}} 一段).

+
+ +

返回值

+ +

返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给{{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}来取消该定时器。

+ +

需要注意的是setTimeout()和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}共用一个编号池,技术上,clearTimeout()和 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 可以互换。但是,为了避免混淆,不要混用取消定时函数。

+ +

在同一个对象上(一个window或者worker),setTimeout()或者setInterval()在后续的调用不会重用同一个定时器编号。但是不同的对象使用独立的编号池。

+ +

例子

+ +

下文的例子在网页中设置了两个简单的按钮,以触发 setTimeout() 和 clearTimeout() 方法:按下第一个按钮会设置一个定时器,定时器在 2s 后显示一个警告对话框,并将此次 setTimeout 的定时器 ID 保存起来,按下第二个按钮可以取消定时器。

+ +

HTML

+ +
<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>
+
+ +
+ +
+ +
+ +
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert('That was really slow!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

结果展示

+ +

{{EmbedLiveSample('例子')}}

+ +

也可参考 clearTimeout() 示例.

+ +

兼容旧环境(polyfill)

+ +

如果你需要向你的回调函数内传递一个或多个参数, 而且还需要兼容那些不支持传递额外参数(不管使用setTimeout() 或者 setInterval())的浏览器时(比如,IE9及更早的版本), 你可以引入下面的兼容代码来支持向定时器函数传参。将以下代码添加到你代码的最上面:

+ +
/*\
+|*|
+|*|  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');
+}())
+ +

针对IE的解决方法

+ +

如果你需要单独的针对IE9及之前浏览器的 hack 写法,你可以使用 JavaScript 条件注释:

+ +
/*@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
+@*/
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

或者使用更加清晰的 IE HTML 条件注释:

+ +
<!--[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]-->
+
+
+
+ +
+ +
+ +

变通方法

+ +

另一种方法是使用匿名函数包裹你的回调函数,这种方式要消耗更多资源:

+ +
var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000);
+
+ +
+ +

上面那个例子也可以用箭头函数:

+ +
var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000);
+
+ +

此外,也可使用 function's bind

+ +
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
+
+ +

关于"this"的问题

+ +

当你向 setTimeout() (或者其他函数)传递一个函数时,该函数中的this指向跟你的期望可能不同,这个问题在 JavaScript reference 中进行了详细解释.

+ +

解释

+ +

setTimeout()调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下为 undefined,这和所期望的this的值是不一样的。

+ +
+

备注:即使是在严格模式下,setTimeout()的回调函数里面的this仍然默认指向window对象, 并不是undefined

+
+ +

查看下面的例子:

+ +
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"
+ +

上面这段代码正常工作,用myArray调用,在函数内,this[sProperty]等于 myArray[sProperty]。然后,下面这个例子:

+ +
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
+ +

myArray.myMethod函数传递给 setTimeout,到了定时时间,this没有指向,默认指向window对象。并且没有方法把 thisArg 传递给setTimeout,正如Array方法的forEachreduce等。下面的例子表示使用call方法设置this也没用。

+ +
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
+ +

可能的解决方案

+ +

一个通用的方法是用包装函数来设置this

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

箭头函数也可以:

+ +
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

另一个解决this问题的方法是使用两个非原生的 setTimeout()setInterval() 全局函数代替原生的。该非原生的函数通过使用Function.prototype.call 方法激活了正确的作用域。下面的代码显示了应该如何替换:

+ +
// 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);
+};
+ +
备注: 这两个替换也让 IE支持了符合 HTML5 标准的定时器函数。所以也能作为一个 polyfills。查看 Callback arguments 一段.
+ +

新特性检测:

+ +
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
+
+ +

针对这个问题并没有原生的解决方案。

+ +
注:JavaScript 1.8.5 引入了 Function.prototype.bind() 方法,该方法允许显式地指定函数调用时 this 所指向的值 。该方法可以帮助你解决 this 指向不确定的问题。
+ +

使用bind()的例子:

+ +
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
+
+ +

备注

+ +

你可以使用 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()","clearTimeout()")}}来取消定时器。

+ +

如果你希望你的代码被重复的调用 (比如每 N 毫秒一次),考虑使用{{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}。

+ +

传递字符串字面量

+ +

setTimeout()传递一个字符串而不是函数会遭受到与使用eval一样的风险.

+ +
// 推荐
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// 不推荐
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

字符串会在全局作用域内被解释执行,所以当setTimeout()函数执行完毕后,字符串中的变量不可用.

+ +

实际延时比设定值更久的原因:最小延迟时间

+ +

有很多因素会导致setTimeout的回调函数执行比设定的预期值更久,本节将讨论最常见的原因。

+ +

最小延时 >=4ms

+ +

在浏览器中,setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。例如:

+ +
function cb() { f(); setTimeout(cb, 0); }
+setTimeout(cb, 0);
+ +
setInterval(f, 0);
+ +

在Chrome 和 Firefox中, 定时器的第5次调用被阻塞了;在Safari是在第6次;Edge是在第3次。Gecko 从这个版本 version 56开始对 setInterval() 开始采用这样的机制(setTimeout()已经实现,具体请参考以下内容)。

+ +

一直以来,不同浏览器中出现这种最小延迟的情况有所不同(例如Firefox) - 从其他地方调用了setInterval( ),或者在嵌套函数调用setTimeout( ) 时(嵌套级别达到特定深度时),都会出现超时延迟。

+ +

如果想在浏览器中实现0ms延时的定时器,你可以参考这里所说的{domxref("window.postMessage()")}}

+ +
+

Note: 最小延时, DOM_MIN_TIMEOUT_VALUE, 是4ms  (但在Firefox中通常是是存储在 dom.min_timeout_value 这个变量中), DOM_CLAMP_TIMEOUT_NESTING_LEVEL 的第5层.

+
+ +
+

Note: 4 ms 是在  HTML5 spec  中精确的,并且在2010年及以后的跨浏览器中保持了一致,这个数值比 {{geckoRelease("5.0")}}规定的嵌套函数的最小延时10ms更为精确。

+
+ +

未被激活的tabs的定时最小延迟>=1000ms

+ +

为了优化后台tab的加载损耗(以及降低耗电量),在未被激活的tab中定时器的最小延时限制为1S(1000ms)。

+ +

Firefox 从version 5 (see {{bug(633421)}}开始采取这种机制,1000ms的间隔值可以通过 dom.min_background_timeout_value 改变。Chrome 从 version 11 (crbug.com/66078)开始采用。

+ +

Android 版的Firefox对未被激活的后台tabs的使用了15min的最小延迟间隔时间 ,并且这些tabs也能完全不被加载。

+ +
+

当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。

+
+ +

追踪型脚本的最小延时限制

+ +

从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 TP lists 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。

+ +

控制这些行为的属性包含以下这些:

+ + + +

超时延迟

+ +

除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 setTimeout()的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:

+ +
function foo() {
+  console.log('foo has been called');
+}
+setTimeout(foo, 0);
+console.log('After setTimeout');
+ +

会在控制台输出:

+ +
After setTimeout
+foo has been called
+ +

出现这个结果的原因是,尽管setTimeout 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。

+ +

WebExtension Background pages和定时器

+ +

在 WebExtension 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在合并到事件驱动后台脚本

+ +

在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:

+ +

1.兼容Chorme。

+ +

2.未来行为的改变会引起问题。

+ +

最大延时值

+ +

包括 IE,  Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}

+
+ +

相关链接:

+ + diff --git a/files/zh-cn/web/api/window/showmodaldialog/index.html b/files/zh-cn/web/api/window/showmodaldialog/index.html new file mode 100644 index 0000000000..81c0bb505f --- /dev/null +++ b/files/zh-cn/web/api/window/showmodaldialog/index.html @@ -0,0 +1,80 @@ +--- +title: Window.showModalDialog() +slug: Web/API/Window/showModalDialog +translation_of: Web/API/Window/showModalDialog +--- +
{{ Fx_minversion_header(3) }} {{ deprecated_header() }}{{APIRef}}
+ +

 Window.showModalDialog() 用于创建和展示一个指向特定网页的模态对话框。

+ +

语法

+ +
returnVal = window.showModalDialog(uri[, arguments][, options]);
+
+ +

其中

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SyntaxDescription
center: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window is centered on the desktop; otherwise it's hidden. The default value is yes.
dialogheight: heightSpecifies the height of the dialog box; by default, the size is specified in pixels.
dialogleft: leftSpecifies the horizontal position of the dialog box in relation to the upper-left corner of the desktop.
dialogwidth: widthSpecifies the width of the dialog box; by default, the size is specified in pixels.
dialogtop: topSpecifies the vertical position of the dialog box in relation to the upper-left corner of the desktop.
resizable: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window can be resized by the user; otherwise its size is fixed. The default value is no.
scroll: {on | off | yes | no | 1 | 0 }If this argument's value is on, yes, or 1, the dialog window has scroll bars; otherwise its size is fixed. The default value is no.
+ +

{{Note("Firefox does not implement the dialogHide, edge, status, or unadorned arguments.")}}

+ +

Compatibility

+ +

Introduced by Microsoft Internet Explorer 4. Support added to Firefox in Firefox 3 (deprectated in Fx 28), and to Safari in Safari 5.1.

+ +

Examples

+ +

Try out showModalDialog().

+ +

Notes

+ +

showModalDialog() is currently being standardized as part of HTML5. The third argument (for additional options) is not present in the HTML5 version, and is (safely) ignored by both Safari and Chrome.

+ +

Specification

+ + diff --git a/files/zh-cn/web/api/window/sidebar/index.html b/files/zh-cn/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..5557b1f26c --- /dev/null +++ b/files/zh-cn/web/api/window/sidebar/index.html @@ -0,0 +1,40 @@ +--- +title: Window.sidebar +slug: Web/API/Window/sidebar +translation_of: Web/API/Window/sidebar +--- +
+ {{APIRef}} {{SeeCompatTable}}
+

Returns a sidebar object, which contains several methods for registering add-ons with browser.

+

Example

+
window.sidebar.addPanel("Google", "http://www.google.com/", "");
+
+

Note: the third empty parameter is required!

+

Notes

+

The sidebar object returned has the following methods:

+ + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription
addPanel(title, contentURL, customizeURL) {{Obsolete_inline(23)}}Adds a sidebar panel. See Creating a Firefox sidebar for details on sidebars in Firefox 2 and later.
addPersistentPanel(title, contentURL, customizeURL) {{Obsolete_inline(23)}}Adds a sidebar panel, which is able to work in the background. This only works in SeaMonkey or Firefox 1.x; Firefox 2 and later will just do addPanel().
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory)Installs a search engine. See Adding search engines from web pages for details.
addMicrosummaryGenerator(generatorURL) {{gecko_minversion_inline("1.8.1")}} {{Obsolete_inline(6)}}Installs a microsummary generator.
+

Specification

+

Mozilla-specific. Not part of any standard.

diff --git a/files/zh-cn/web/api/window/sizetocontent/index.html b/files/zh-cn/web/api/window/sizetocontent/index.html new file mode 100644 index 0000000000..19932356f6 --- /dev/null +++ b/files/zh-cn/web/api/window/sizetocontent/index.html @@ -0,0 +1,38 @@ +--- +title: Window.sizeToContent() +slug: Web/API/Window/sizeToContent +translation_of: Web/API/Window/sizeToContent +--- +
{{APIRef}}{{Non-standard_header}}
+ +

The Window.sizeToContent() 方法根据窗口内容调整窗口大小。 为了使其工作,在调用此函数时应加载DOM内容,例如,一旦抛出 {{event("DOMContentLoaded")}} 事件。

+ +

可以强行的调整窗口的最小尺寸。

+ +

语法

+ +
window.sizeToContent()
+
+ +

 例子

+ +
window.sizeToContent();
+
+ +

 规范说明

+ +

此功能不是任何规范的一部分

+ +

浏览器兼容说明

+ +
+ + +

{{Compat("api.Window.sizeToContent")}}

+
+ +

其他链接

+ + diff --git a/files/zh-cn/web/api/window/stop/index.html b/files/zh-cn/web/api/window/stop/index.html new file mode 100644 index 0000000000..dc65485d75 --- /dev/null +++ b/files/zh-cn/web/api/window/stop/index.html @@ -0,0 +1,52 @@ +--- +title: Window.stop() +slug: Web/API/Window/stop +tags: + - API + - DOM + - Window + - 参考 + - 方法 +translation_of: Web/API/Window/stop +--- +
 {{APIRef}}
+ +

window.stop() 方法的效果相当于点击了浏览器的停止按钮。由于脚本的加载顺序,该方法不能阻止已经包含在加载中的文档,但是它能够阻止图片、新窗口、和一些会延迟加载的对象的加载。

+ +

语法

+ +
window.stop()
+
+ +

示例

+ +
window.stop();
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','browsers.html#dom-window-stop','Window.stop()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-stop', 'Window.stop')}}{{Spec2('HTML5 W3C')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.stop")}}

diff --git a/files/zh-cn/web/api/window/storage_event/index.html b/files/zh-cn/web/api/window/storage_event/index.html new file mode 100644 index 0000000000..81d66d57bc --- /dev/null +++ b/files/zh-cn/web/api/window/storage_event/index.html @@ -0,0 +1,85 @@ +--- +title: storage +slug: Web/API/Window/storage_event +tags: + - Web Storage + - 事件 +translation_of: Web/API/Window/storage_event +--- +

当存储区域(localStorage 或 sessionStorage)被修改时,将触发 storage 事件。查看 Web Storage API 来获取更多信息。

+ +

常规信息

+ +
+
说明
+
Web Storage
+
接口
+
{{domxref("StorageEvent")}}
+
是否冒泡
+
No
+
默认行为可取消
+
No
+
目标
+
DefaultView (<window>)
+
默认行为
+
+
+ +

属性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}事件目标(DOM 树中的最大目标)
type {{readonlyInline}}{{domxref("DOMString")}}事件的类型
bubbles {{readonlyInline}}{{jsxref("Boolean")}}事件通常是否会出现冒泡
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可取消
key {{readonlyInline}}{{domxref("DOMString")}} (string)键更改时
oldValue {{readonlyInline}}{{domxref("DOMString")}} (string)正在更改键的旧值
newValue {{readonlyInline}}{{domxref("DOMString")}} (string)正在更改键的新值
url {{readonlyInline}}{{domxref("DOMString")}} (string)键更改的文档的地址
storageArea {{readonlyInline}}{{domxref("Storage")}}受影响的存储对象
diff --git a/files/zh-cn/web/api/window/top/index.html b/files/zh-cn/web/api/window/top/index.html new file mode 100644 index 0000000000..d2142ec21e --- /dev/null +++ b/files/zh-cn/web/api/window/top/index.html @@ -0,0 +1,55 @@ +--- +title: Window.top +slug: Web/API/Window/top +tags: + - API + - HTML DOM + - Property + - Reference + - Window +translation_of: Web/API/Window/top +--- +

{{APIRef}}

+ +

返回窗口层级最顶层窗口的引用。

+ +

语法

+ +
var topWindow = window.top;
+
+ +

备注

+ +

 window.parent 返回当前窗口的直接父对象,而 {{domxref("window.top")}} 返回最顶层的窗口对象。

+ +

 

+ +

当你在处理父窗口的子框架(subframe),而你想获取顶层框架时,这个属性相当有用。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'browsers.html#dom-top', 'window.top')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#dom-top', 'window.top')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.Window.top")}}

diff --git a/files/zh-cn/web/api/window/updatecommands/index.html b/files/zh-cn/web/api/window/updatecommands/index.html new file mode 100644 index 0000000000..29eaef7dbf --- /dev/null +++ b/files/zh-cn/web/api/window/updatecommands/index.html @@ -0,0 +1,37 @@ +--- +title: Window.updateCommands() +slug: Web/API/Window/updateCommands +tags: + - chrome窗口(UI)的命令状态。 +translation_of: Web/API/Window/updateCommands +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

概要

+ +

更新当前chrome窗口(UI)的命令状态。

+ +

语法

+ +
window.updateCommands("sCommandName")
+
+ +

 参数

+ + + +

记录

+ +

这将启用或禁用项目(根据需要在命令节点上设置或清除“disabled”属性),或通过在XUL命令节点的“state”属性中设置当前状态信息来确保命令状态反映选择的状态。

+ +

规范

+ +

DOM 0 级。不属于规范。

+ +

浏览器兼容性

+ + + +

{{Compat("api.Window.updateCommands")}}

diff --git a/files/zh-cn/web/api/window/url/index.html b/files/zh-cn/web/api/window/url/index.html new file mode 100644 index 0000000000..6bf90043c3 --- /dev/null +++ b/files/zh-cn/web/api/window/url/index.html @@ -0,0 +1,104 @@ +--- +title: Window.URL +slug: Web/API/Window/URL +tags: + - Window.URL +translation_of: Web/API/URL +--- +

{{ApiRef("Window")}}{{SeeCompatTable}}

+ +

Window.URL 属性返回一个对象,它提供了用于创建和管理对象URLs的静态方法。它也可以作为一个构造函数被调用来构造 {{domxref("URL")}} 对象。

+ +
+

Note: 此功能在Web Workers中可用。

+
+ +

语法

+ +

调用一个静态方法:

+ +
img.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(blob);
+ +

构造一个新对象:

+ +
var url = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url', 'URL')}}{{Spec2('URL')}}Initial definition
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0[2]{{CompatGeckoDesktop("2.0")}}[1]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0[2]6.0[2]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("14.0")}}[1]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
+
+ +

[1] 从 Gecko 2 (Firefox 4) 到 包括Gecko 18, Gecko 返回一个不标准的nsIDOMMozURLProperty内部类型. 在实践中, 这是没有意义的.

+ +

[2] 在非标准名称webkitURL下实现。

+ +

也可以看看

+ + diff --git a/files/zh-cn/web/api/window/visualviewport/index.html b/files/zh-cn/web/api/window/visualviewport/index.html new file mode 100644 index 0000000000..bc751840d9 --- /dev/null +++ b/files/zh-cn/web/api/window/visualviewport/index.html @@ -0,0 +1,89 @@ +--- +title: Window.visualViewport +slug: Web/API/Window/visualViewport +translation_of: Web/API/Window/visualViewport +--- +

{{SeeCompatTable}}{{APIRef("Visual Viewport")}}

+ +

 

+ +

{{domxref("Window")}} 接口的visualViewport只读属性返回一个{{domxref("VisualViewport")}}对象,该对象表示给定窗口的可视视口。

+ +

语法

+ +
var visualViewport = Window.visualViewport
+ +

+ +

一个 {{domxref("VisualViewport")}} 对象。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Visual Viewport','#dom-window-visualviewport','visualViewport')}}{{Spec2('Visual Viewport')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/zh-cn/web/api/window/window.blur()/index.html b/files/zh-cn/web/api/window/window.blur()/index.html new file mode 100644 index 0000000000..0aebdbb367 --- /dev/null +++ b/files/zh-cn/web/api/window/window.blur()/index.html @@ -0,0 +1,39 @@ +--- +title: Window.blur() +slug: Web/API/Window/Window.blur() +translation_of: Web/API/Window/blur +--- +

{{APIRef}}

+ +

总结

+ +

将焦点移出顶层窗口。

+ +

语法

+ +
window.blur()
+ +

示例

+ +
window.blur();
+ +

注意

+ +

使用 window.blur() 方法与用户主动将焦点移出顶层窗口本质上是一样的。

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','interaction.html#dom-window-blur','Window.blur()')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/zh-cn/web/api/window/window/index.html b/files/zh-cn/web/api/window/window/index.html new file mode 100644 index 0000000000..e3cab55da4 --- /dev/null +++ b/files/zh-cn/web/api/window/window/index.html @@ -0,0 +1,65 @@ +--- +title: Window.window +slug: Web/API/Window/window +translation_of: Web/API/Window/window +--- +
{{APIRef}}
+ +

摘要

+ +

window对象的 window 属性指向这个window对象本身。因此以下表达式所返回的window对象都是同一个。

+ +
window.window
+window.window.window
+window.window.window.window
+  ...
+
+
+ +

在网页中,window对象也是一个全局对象。这意味着:

+ +
    +
  1. 脚本中的全局变量实际上是window对象的属性: +
    var global = {data: 0};
    +alert(global === window.global); // displays "true"
    +
    +
  2. +
  3. 不用写 window. 前缀就可以访问window对象的内置属性: +
    setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout.
    +alert(window === window.window); // displays "true"
    +
    +
  4. +
+ +

将 window 属性指向该window对象本身的目的,是为了更容易引用全局对象。不然,就得在最开始写代码的时候进行手动赋值:var window = this; 。

+ +

另外一个原因是如果没有这个属性,就不能像这样方便的写:  {{domxref("window.open","window.open('http://google.com/')")}},而只能这样: open('http://google.com/')

+ +

使用该属性还有一个原因,有些库,特别是JavaScript模块希望能够提供OOP版本和非OOP版本。例如,如果引用了 this.window.location.href ,JavaScript 模块就可以在它定义的类里面定义一个 window 属性(因为默认没有全局性的 window 变量存在),这个属性可以在将window对象传进这个模块的类的构造器之后被创建。这样,这个类的方法中的 this.window 就指向了window对象。在没有命名空间的版本中,this.window 会重新指向window对象,从而很容易获取到文档的位置。还有一个优点,这个类(即使这个类定义在模块外面)的对象可以随意地改变对window的引用,而如果有一个写死了的window的引用就做不到这样。类内部的默认值仍然可以设置成当前的window对象。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
规范状态说明
{{SpecName('HTML WHATWG', '#dom-window', 'Window.window')}}{{Spec2('HTML WHATWG')}}和最新版 {{SpecName("HTML5.1")}}一致
{{SpecName('HTML5.1', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5.1')}}和{{SpecName("HTML5 W3C")}}一致
{{SpecName('HTML5 W3C', 'browsers.html#dom-window', 'Window.window')}}{{Spec2('HTML5 W3C')}}第一个包含 Window.window 定义的快照
-- cgit v1.2.3-54-g00ecf