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>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>
 
		 随时随地看视频
随时随地看视频 
				 
				 
				 
				 
				