說明:目前三大主流瀏覽器中firefox和IE都支持onbeforeunload事件,opera尚未支持。
用法:
·object.onbeforeunload = handler
·<element onbeforeunload = “handler” … ></element>
描述:
事件觸發的時候彈出一個有確定和取消的對話框,確定則離開頁面,取消則繼續待在本頁。handler可以設一個返回值作爲該對話框的顯示文本。
·關閉瀏覽器窗口
·通過地址欄或收藏夾前往其他頁面的時候
·點擊返回,前進,刷新,主頁其中一個的時候
·點擊 一個前往其他頁面的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
平臺支持:
IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+
示例:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onbeforeunload測試</title>
<script>
function checkLeave(){
event.returnValue="確定離開當前頁面嗎?";
}
</script>
</head>
<body onbeforeunload="checkLeave()">
</body>
</html>
但是onbeforeunload有個小毛病,就是頁面刷新時,他還是會調用到onbeforeunload,爲什麼?其實刷新就相當於關閉了這個IE再重新打開的意思,因此還是會調用到onbeforeunload。
究竟怎麼解決刷新不調用onbeforeunload呢?
網上提供很多方法,本人覺得最實用還是以下這段JS
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey)
{
alert("是關閉而非刷新");
window.event.returnValue = "是否關閉?";
}else{
alert("是刷新而非關閉");
}
}
用法:
·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的表單的時候。
示例:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onunload測試</title>
<script>
function checkLeave(){
alert("歡迎下次再來!");
}
</script>
</head>
<body onunload="checkLeave()">
</body>
</html>