JS 是否离开当前页面

对于一些特殊页面,如考试页面,如果用户点击其它链接或关闭当前窗口,我们都希望给出提示,让用户选择是否确定要离开当前页面,脑海中可能已经出现confirm了吧……

其实具体实现很简单,因为具体方法浏览器已经为我们封装好了:beforeunload | onbeforeunload event

<!DOCTYPE html>
<html>
<head>
<script>
  function closeIt()
  {
    return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
  }
  window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com">Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>
chrome
IE11
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容