无法在 IE8 中禁用 F5 键

Unable to disable F5 key in IE8

本文关键字:F5 IE8      更新时间:2023-09-26

我想在我的 Web 应用程序中禁用 F5 键。我正在使用以下代码:

<html>
<head>
<script type="text/javascript">
window.onkeydown=function(e) {
               if (e.keyCode === 116 ) {
                       alert("This action is not allowed");
                       e.keyCode = 0;
                       e.returnValue = false;                  
                       return false;
                   }
               }
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>

上面的代码在Chrome中工作正常,但在IE8中它不起作用。按 F5 时,页面将在 IE8 上刷新。我尝试使用e.preventDefault(),但没有任何效果。有什么帮助吗??

尝试下一个代码:

<html>
<head>
<script type="text/javascript">
  document.onkeydown=function(e) {
    e=e||window.event;
    if (e.keyCode === 116 ) {
      e.keyCode = 0;
      alert("This action is not allowed");
      if(e.preventDefault)e.preventDefault();
      else e.returnValue = false;
      return false;
    }
  }
</script>
</head>
<body>
<p> F5 Test IE8</p>
</body>
</html>
  • 必须使用document对象而不是window对象。在IE8中window对象不支持onkeydown
  • 您必须使用e=e||window.event;代码行,因为在IE8中-当事件注册为element.on...时,事件处理程序函数中没有接收到任何参数(e您的示例中undefined
  • );

在IE8,Firefox和chrome中测试:

document.onkeydown=function(e) {
    var event = window.event || e;
    if (event.keyCode == 116) {
        event.keyCode = 0;
        alert("This action is not allowed");
        return false;
    }
}

另请参阅此示例。