简体   繁体   English

在浏览器中禁用退格导航

[英]Disable backspace navigation in browser

Does anyone know how to disable the ability to use the "backspace" key on your keyboard to navigate to the previous page you were on? 有谁知道如何禁用使用键盘上的“退格”键导航到上一页的功能?

Right now, I have an invoice type web application, that if the user(on a mac) hits backspace to remove an element within a form field, after reaching the end of the entered item, if they hit the backspace again, it moves to the prior browsed page, making them lose data with the application that was entered. 现在,我有一个发票类型的Web应用程序,如果用户(在Mac上)按下退格键以删除表单字段中的元素,则在到达输入项的末尾后,如果他们再次按下退格键,它将移至先前浏览过的页面,使他们丢失了所输入应用程序的数据。

window.onkeydown = function(e) {
  if (e.keyCode == 8 && e.target == document.body)
    e.preventDefault();
}

Explanation: The backspace key has keycode 8. Calling "preventDefault" means that the event does not cause the default behaviour of pressing the backspace key (ie navigating back a page). 说明:退格键的键码为8。调用“ preventDefault”意味着该事件不会导致按下退格键的默认行为(即,向后导航页面)。 This behaviour only happens if the target of the event is the document's body. 仅当事件的目标是文档的正文时,才会发生此行为。

Edit: jsfiddle example 编辑: jsfiddle示例

The downside to @Sam's answer is that if you click on an HTML element, such as a table, the Backspace key still takes you back. @Sam答案的缺点是,如果您单击HTML元素(例如表格),则Backspace键仍会使您返回。 It only works if you click in a "clear space" that does not have any HTML elements. 仅当您单击没有任何HTML元素的“空白”时,它才起作用。

I tweaked Sam's answer and took code from this answer to create this solution. 我调整了Sam的答案,并从该答案中获取了代码以创建此解决方案。 It does not cover all edge cases, but it was enough for my use case. 它并没有涵盖所有的极端情况,但是对于我的用例来说已经足够了。

function disableBackspaceNavigation() {
  window.onkeydown = function(e) {
    if (e.keyCode == 8 && !isTextBox(e.target)) e.preventDefault();
  }
}

function isTextBox(element) {
  var tagName = element.tagName.toLowerCase();
  if (tagName !== "input") return false;

  var typeAttr = element.getAttribute('type').toLowerCase();
  return typeAttr === 'text';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM