美文网首页
JS 是否离开当前页面

JS 是否离开当前页面

作者: 大水啊大水 | 来源:发表于2017-05-15 14:58 被阅读46次

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

相关文章

网友评论

      本文标题:JS 是否离开当前页面

      本文链接:https://www.haomeiwen.com/subject/evdhxxtx.html