使用纯 JavaScript 在文本字段或文本区域具有焦点时禁用键盘快捷键

any*_*y_h 8 javascript textarea focus input

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

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;
};
Run Code Online (Sandbox Code Playgroud)

但当我有文字inputtextarea焦点集中时它也有效。聚焦时禁用键盘快捷键的最佳方法是什么?

谢谢!

Tha*_*ung 5

禁用文档输入的事件传播

nextEl.onkeyup = prevEl.onkeyup = function(e){ e.stopPropagation(); };
Run Code Online (Sandbox Code Playgroud)