Heim  >  Artikel  >  Web-Frontend  >  用js判断页面刷新或关闭的方法(onbeforeunload与onunload事件)_javascript技巧

用js判断页面刷新或关闭的方法(onbeforeunload与onunload事件)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:52:181320Durchsuche

Onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。 <BR>  Onbeforeunload也是在页面刷新或关闭时调用,Onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而onunload则已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用。Onunload是无法阻止页面的更新和关闭的。而 Onbeforeunload 可以做到。 <br><br>页面加载时只执行onload <BR>页面关闭时先执行onbeforeunload,最后onunload <BR>页面刷新时先执行onbeforeunload,然后onunload,最后onload。 <br><br><STRONG>1、onbeforeunload事件: <BR>  说明:目前三大主流浏览器中firefox和IE都支持onbeforeunload事件,opera尚未支持。 <BR>  用法: <BR>   ·object.onbeforeunload = handler <BR>   ·<element onbeforeunload = “handler” … > <BR>  描述: <BR>   事件触发的时候弹出一个有确定和取消的对话框,确定则离开页面,取消则继续待在本页。handler可以设一个返回值作为该对话框的显示文本。 <br><br>  触发于: <BR>   ·关闭浏览器窗口 <BR>   ·通过地址栏或收藏夹前往其他页面的时候 <BR>   ·点击返回,前进,刷新,主页其中一个的时候 <BR>   ·点击 一个前往其他页面的url连接的时候 <BR>   ·调用以下任意一个事件的时候:click,document write,document open,document close,window close ,window navigate ,window NavigateAndFind,location replace,location reload,form submit. <BR>   ·当用window open打开一个页面,并把本页的window的名字传给要打开的页面的时候。 <BR>   ·重新赋予location.href的值的时候。 <BR>   ·通过input type=”submit”按钮提交一个具有指定action的表单的时候。 <BR>  可以用在以下元素: <BR>   ·BODY, FRAMESET, window <BR>  平台支持: <BR>   IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+ <BR>  示例: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="88705" class="copybut" id="copybut88705" onclick="doCopy('code88705')"><U>复制代码 代码如下:<div class="codebody" id="code88705"> <BR>   <html xmlns="http://www.w3.org/1999/xhtml"> <BR>   <head> <BR>   <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <BR>   <title>onbeforeunload测试 <BR>   <script> <BR>   function checkLeave(){ <BR>    event.returnValue="确定离开当前页面吗?"; <BR>   } <BR>   </script>
   
   


   
   
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn