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/beforeunloadevent/index.html | 71 ++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 files/zh-cn/web/api/beforeunloadevent/index.html (limited to 'files/zh-cn/web/api/beforeunloadevent/index.html') diff --git a/files/zh-cn/web/api/beforeunloadevent/index.html b/files/zh-cn/web/api/beforeunloadevent/index.html new file mode 100644 index 0000000000..69626e0ec7 --- /dev/null +++ b/files/zh-cn/web/api/beforeunloadevent/index.html @@ -0,0 +1,71 @@ +--- +title: BeforeUnloadEvent +slug: Web/API/BeforeUnloadEvent +tags: + - API + - BeforeUnloadEvent + - 参考 +translation_of: Web/API/BeforeUnloadEvent +--- +

{{APIRef}}

+ +

beforeunload 事件触发于 window、document 和它们的资源即将卸载时。 

+ +

当事件属性 returnValue 被赋值为非空字符串时,会弹出一个对话框,让用户确认是否离开页面(示例如下)。否则,事件被静默处理。一些浏览器实现仅在框架或内置框架接收到用户手势或交互时才显示对话框。在 {{anch("浏览器兼容性")}} 中查看更多信息。

+ + + + + + + + + + + + + + + + + + + + +
BubblesNo
CancelableYes
Target objectsdefaultView
Interface{{domxref("Event")}}
+ +

示例

+ +
window.addEventListener("beforeunload", function( event ) {
+  event.returnValue = "\o/";
+});
+
+//等同于
+window.addEventListener("beforeunload", function( event ) {
+  event.preventDefault();
+});
+
+ +

基于 Webkit 的浏览器没有遵循该弹窗规范。以下是一个基本跨浏览器运行的例子。

+ +
window.addEventListener("beforeunload", function (e) {
+  var confirmationMessage = "\o/";
+
+  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
+  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
+});
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf