网上找的
1.用javascript重新定义 window.onbeforeunload() 事件
在javascript里定义一个函数即可 (只在页面关闭时执行,刷新时不执行。)
- function window.onbeforeunload() { alert("关闭窗口")}
- alert()事件将会在关闭窗口前执行,你也可以用户决定是否关闭窗口
- function window.onbeforeunload() {
- if (event.clientX>document.body.clientWidth && event.clientY<0 ||event.altKey) //这个方法好像只适用于ie6,但ie7和firefox不能用,firefox是因为要为1.方法传入event才能用event,2.在文档外(document)外就没有event的clientX,clentY,X,Y
- window.event.returnValue="确定要退出本页吗?";
- }
2.用onUnload方法
在body 标签里加入onUnload事件
- body onUnload="myClose()"
然后在javascript里定义myClose()方法
但是onUnload方法是在关闭窗口之后执行,不是在关闭窗口之前执行,如果你想在关闭窗口之前做判断,请用第一种方法
以上的方法在ie6中,在页面刷新时候 不会调用是因为event.clientX>document.body.clientWidth
适用于firefox和ie的
- function getEvent() //同时兼容ie和ff的写法, 这个方法是网上copy的
- {
- if(document.all) return window.event;
- func=getEvent.caller;
- while(func!=null){
- var arg0=func.arguments[0];
- if(arg0)
- {
- if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))
- {
- return arg0;
- }
- }
- func=func.caller;
- }
- return null;
- }
- function ConfirmClose() {
- if(window.event)
- window.event.returnValue = "在关闭窗口前确认您是否已经保存了信息!";
- else
- getEvent().preventDefault();//for firefox
- }
- function on_page_loaded() //自己定义的body的onload事件
- {
- try{
- if(!window.onbeforeunload ) //为了不覆盖原来的onbeforeunload方法,先判断
- window.onbeforeunload = ConfirmClose; //todo 增加了窗口关闭前的提示
- }catch(e){}
- }
- <body onload="on_page_loaded()">
或者简单些
- function ConfirmClose() {
- return "在关闭窗口前确认您是否已经保存了信息!";
- }
- function on_page_loaded()
- {
- try{
- if(!window.onbeforeunload)
- window.onbeforeunload = function(){return ConfirmClose();}; //todo 增加了窗口关闭前的提示
- }catch(e){}
- }
- <body onload="on_page_loaded()">
但是页面刷新的时候也会调用的
在搞这个的时候才发现body没有onclick事件,应该用document.onclick=function(){}