在beforeunload事件里,不需要alert,该事件会自动产生一个弹出框,
就算你加了alert也是没效果的。
另外,要使beforeunload事件能自动弹出框,必须得有返回值,如:
1
2
3
4
5
|
$(window).beforeunload(
function
(event){
var
message = “I’m really going to miss you
if
you go.”;
event.returnValue = message;
return
message;
});
|
上面的代码可以达到关闭、点击链接、输入地址都窗口弹出框的效果。
把返回值message设为你想显示的信息
- window.onunload = function() {
- // 要执行的代码
- }
window.onunload = function() {
// 要执行的代码
}
如果是jQuery:
- $(window).unload(function (evt) {
- // 要执行的代码
- });
- $(window).unload(function (evt) {
- if (typeof evt == 'undefined') {
- evt = window.event;
- }
- if (evt) {
- var n = window.event.screenX - window.screenLeft;
- var b = n > document.documentElement.scrollWidth-20;
- if(b && window.event.clientY < 0 || window.event.altKey){
- // 这个可以排除刷新 关闭的时候触发
- }
- }
- });
onunload,onbeforeunload 在页面刷新或关闭时调用,区别在于:
onbeforeunload 是在页面刷新或关闭前触发,这时浏览器并未请求服务器读取新页面,因此onbeforeunload是可以阻止页面更新或关闭的。
onunload 也是在页面刷新或关闭时触发,不过这时浏览器已经向服务器请求读取新页面,因此onunload是无法阻止页面更新或关闭的。
1. onbeforeunload 事件
事件触发时会弹出一个有确定和取消的对话框,确定后才会执行后续事件,否则继续留在本页。
触发于:
- 关闭浏览器窗口
- 通过地址栏或收藏夹前往其他页面的时候
- 点击返回,前进,刷新,主页其中一个的时候
- 点击 一个前往其他页面的url连接的时候
- 调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
- 当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
- 重新赋予location.href的值的时候。
- 通过input type=”submit”按钮提交一个具有指定action的表单的时候。
可以用在以下元素:
- BODY, FRAMESET, window
平台支持:IE,Firefox,Chrome,Safari。Opera暂不支持。
例子:
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title> 刷新与离开页面检测 </title>
- </head>
- <body>
- <script type="text/javascript">
- window.onbeforeunload = function(){
- return '你的文章尚未保存';
- }
- </script>
- </body>
- </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title> 刷新与离开页面检测 </title>
</head>
<body>
<script type="text/javascript">
window.onbeforeunload = function(){
return '你的文章尚未保存';
}
</script>
</body>
</html>
2. onunload 事件
事件触发时,会弹出一个只有确定的对话框,点确定后执行后续事件。
触发于:
- 关闭浏览器窗口
- 通过地址栏或收藏夹前往其他页面的时候
- 点击返回,前进,刷新,主页其中一个的时候
- 点击 一个前往其他页面的url连接的时候
- 调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit.
- 当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。
- 重新赋予location.href的值的时候。
- 通过input type=”submit”按钮提交一个具有指定action的表单的时候。
平台支持:只有IE,其他都不支持。
例子:
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8">
- <title> 刷新与离开页面检测 </title>
- </head>
- <body>
- <script type="text/javascript">
- window.onunload = function(){
- alert('谢谢下次再来');
- }
- </script>
- </body>
- </html>