---
title: "onunload,onbeforeunload事件的使用实例"
author: "alwarse"
date: "2012-05-29T14:41:45Z"
tags: []
categories: ["Web前端"]
slug: "onunload-onbeforeunload"
draft: false
lastmod: "2012-05-29T14:41:45Z"
id: 1543917
url: "https://alwarse.iteye.com/blog/1543917"
---

onunload,onbeforeunload这两个事件基本相似都遵循这样的准则：

<!--用法：
　　　·object.onbeforeunload = handler
　　　·<element onbeforeunload = "handler"></element> 　　描述：
　　　当用户关闭一个页面时触发 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的表单的时候。
-->

//他们的区别我想可能就是对事件加返回值的时候吧，onbeforeunload会弹出判断框而onunload则不会。

1、unload的使用例子：

　　<html xmlns="<http://www.w3.org/1999/xhtml>">
　　　<head>
　　　<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
　　　<title>onunload测试</title>
　　　<script>
　　　function checkLeave(){
     　　　　alert("欢迎下次再来！");
   /*if(event.clientX>document.body.clientWidth)
   {
   alert('浏览器关闭');
   }*/
　　　}
　　　</script>
　　　</head>
　　　<body onunload="checkLeave()">
　　　<a href="#" onclick="alert('aa')">aa</a>
　　　</body>
　　　</html>

2、onbeforeunload的使用例子：

<html>
<head>
<title>onunload..</title>
</head>
<body /*onunload="if(confirm('你确定要离开本页?')){return 'aa'}else{return 'bb'}"*/>
<script>/*onload=alert("正在加载页面,请等待...")*/</script>
<script type="text/javascript">

document.body.onbeforeunload=function(){
/*if(confirm('你确定要离开本页?')){
   return true;
}else{
   return false;
} */
           /*if(event.returnValue == false)
            {
       alert('没有返回值');
               } */
//如果在刷新的时候不想弹出对话框,可以这样写
   if(event.clientX>document.body.clientWidth) //条件相当于点叉的时候
   {
   alert('浏览器关闭');
   }
   else
   {
   alert('浏览器刷新');}


   /*
              if (event.clientX > document.body.clientWidth - 50 && event.clientY<0||event.altKey)
               {
//在 .CS文件中对应了一个方法，更改在线状态的
                // <%=exitLogin()%>;

               }
               else
               {
                  alert("刷新或者跳转到其他页");
               }
   */

   //return "您确定要离开这个页面吗（文字提示）"; 当有返回值的时候此方法onbeforeunload会自动弹出确定是否关闭对话框
   //event.returnValue="确定离开当前页面吗？"; 同return
}

</script>
</body>
</html>
http://hi.baidu.com/sch362017466/blog/item/eee0eecf9db54333b600c819.html