当文本字段或文本区域使用纯 JavaScript 获得焦点时禁用键盘快捷键

问题描述 投票:0回答:2

我有一个简单的脚本,它使用向左和向右箭头移动到下一篇和上一篇博文。

var nextEl = document.getElementById("pagination__next__link");
var prevEl = document.getElementById("pagination__prev__link");

document.onkeyup = function(e) {

    if (nextEl !== null) {
        if (e.keyCode === 37) {
            window.location.href = nextEl.getAttribute('href');
        }
    }
    if (prevEl !== null) {
        if (e.keyCode === 39) {
            window.location.href = prevEl.getAttribute('href');
        }
    }
    return false;
};

但是当我有文字

input
textarea
重点时,它也有效。聚焦时禁用键盘快捷键的最佳方法是什么?

谢谢!

javascript input focus textarea
2个回答
5
投票

禁用文档输入的事件传播

nextEl.onkeyup = prevEl.onkeyup = function(e){ e.stopPropagation(); };

0
投票

为了解决所有文本输入和文本区域的问题,我最终使用了以下代码片段:

  // prevent shortcuts from interfering with typing in text inputs or textareas
  document.documentElement.addEventListener(
    "keydown",
    (ev) => {
      if (
        ev.target &&
        (ev.target instanceof HTMLTextAreaElement ||
          (ev.target instanceof HTMLInputElement && (!ev.target.type || ev.target.type === "text")))
      ) {
        ev.stopPropagation()
      }
    },
    true,
  )
© www.soinside.com 2019 - 2024. All rights reserved.