用JS实现在页面关闭或刷新时触发特定的事件

 用JS实现在页面关闭或刷新时触发特定的事件
 <script type="text/javascript">
window.onbeforeunload = function()  
{  
  var n = window.event.screenX - window.screenLeft;  
  var b = n > document.documentElement.scrollWidth-20;  
  if(b && window.event.clientY < 0 || window.event.altKey)  
  {  
          alert("是关闭而非刷新");  
          document.getElementById("ButtonClear").click(); 
        //window.event.returnValue = "";  
  }
else  
  {  
      alert("是刷新而非关闭");  
  }  
}
  
 </script>
 
注:在用document.getElementById("ButtonClear").click(); 时出现为对象为空,意思就是未找到这个按钮,发现原因是在按钮的属性里设置了Visable="false",应该将其改为:style="display:none"
 
因此在这里要比较一下按钮的 Visable="false" 属性和 style="display:none" 属性设置的区别:
style="display:none"仅仅是隐藏了控件,但是html代码依然生成,而 Visable="false"  就直接不生成html控件,也就是页面上没有这个控件对象了。
 
所以,如果要用document.getElementById("ButtonClear").click(); 的话,就只能将按钮的属性设置成为style="display:none"
原文地址:https://www.cnblogs.com/xiaopanlyu/p/2950842.html