运用onunload事件判断浏览器是刷新还是关闭窗口
转载自:http://xieyu.blog.51cto.com/213338/55798?当浏览器退出时会触发onunload事件,因此我们可以使用onunload事件做一些在页面关闭时要执行的操作,如提示用户信息等。但或许在实际应用中我们都发现一个问题,刷新浏览器同样会触发onunload事件,也就是只要是离开该页面就会触发onunload事件,或许刷新时我们并不想执行onunload定义的操作,或者我们只想在刷新时执行某操作,这样我们就遇到了一些麻烦。
?????? 下面就把找到的两段代码共享出来,希望对正好需要解决此问题朋友有所帮助。
方法一:<HTML>?
?????? <HEAD>?
????????????? <TITLE>判断是刷新还是关闭-[url]www.51windows.Net</TITLE>?[/url]
????????????? <meta http-equiv="Content-Type" content="text/html; charset=gb2312">?
????????????? <META NAME="Author" CONTENT="51windows,海娃,haiwa">?
????????????? <META NAME="Description" CONTENT="Power by 51windows.Net">?
?????? </HEAD>?
?????? <script>?
????????????? function CloseOpen(event) {?
???????????????????? if(event.clientX<=0 && event.clientY<0) {?
??????????????????????????? alert("关闭");?
???????????????????? }?
???????????????????? else?
???????????????????? {?
??????????????????????????? alert("刷新或离开");?
???????????????????? }?
????????????? }?
?????? </script>?
?????? <body onunload="CloseOpen(event)">?
?????? </BODY>
</HTML>
第二种做法:<script language="javascript">?
?????? window.onbeforeunload = function() //author: meizz?
?????? {?
????????????? 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 = ""; //这里可以放置你想做的操作代码?
????????????? }?
?????? }
</script>