如何让按键在输入字段上不起作用

How to have keypresses not work on input fields

我只想在我的 Reddit 用户脚本中添加一个简单的功能,使我能够在 post 上按 E 并单击赞成按钮,我设法在 [=31= 中使用此代码完成了此操作] 但当我在任何输入字段中输入时它也有效,我不知道如何让它停止。

代码:

$(document).ready(()=>{
  $(document).keypress((e)=>{
      if(e.key === 'e'){
          //$('.voteButton[data-click-id="upvote"]')[0].click();
          console.log('clicked!');
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" />

注意: 这应该是重复的问题确实帮助了我,但没有直接解决我的问题,添加 if($(e.target).is('input,select,button,textarea,div[role="textbox"]')) return; 是解决问题的方法,显然 Reddit 对文本字段使用包装器,所以我不得不添加 div[role="textbox"],这是使用的 "textbox",问题是我将不得不为所有这些包装元素手动添加自定义选择。

我编辑了答案,我认为您只是想在输入中输入事件

你可以 select 像这样使用 id 输入

$(document).ready(() => {
  $("document").keypress(e => { 
    if (e.key === "e") {
      if($("#input").is(":focus")) return null // here is change 
      //$('.voteButton[data-click-id="upvote"]')[0].click();
      console.log("clicked!");
    }
  });
});
    <input id="input" type="text" />  // here a change to your code

您可以尝试如果事件元素是输入然后退出函数:

$(document).ready(()=>{
  $(document).keypress((e)=>{
      if($(e.target).is('input')) return
      if(e.key === 'e'){
          //$('.voteButton[data-click-id="upvote"]')[0].click();
          console.log('clicked!');
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>