JavaScript 阻止 Keyup 的默认值

javascript prevent default for keyup

本文关键字:默认值 Keyup 阻止 JavaScript      更新时间:2023-09-26

我有以下代码:

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true"></p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        alert("Should remove element.");
        $(this).remove();
        $(this).previous('p').focus();
    };
});

我想阻止按下某个键时的默认操作。 preventDefault适用于keypress,但不适用于keyup。有没有办法防止$(document).on('keyup')的失败?

No. keyup在默认操作后触发。

keydownkeypress是您可以防止默认值的地方。
如果未停止这些操作,则会发生默认值并触发keyup

我们可以使用以下代码片段来阻止该操作。

e.stopPropagation();
      e.preventDefault();  
      e.returnValue = false;
      e.cancelBubble = true;
      return false;
按键

在按下/按键后触发。我们可以阻止任何事件中的默认操作。

谢谢

湿 婆