简体   繁体   English

防止功能onkeydown javascript

[英]Prevent function onkeydown javascript

Hello I'm new to this and I have a script that will fire function on keydown. 您好,我是新手,我有一个脚本可以在按下key键时触发功能。 But I also have an input text field box and if I'm typing in that input field box and press the key to that fires the function. 但是我还有一个输入文本字段框,如果要在该输入字段框中键入内容,然后按该键即可触发该功能。 The function fires but I don't want the function to fire if I'm typing in the input field would there be a way to do this? 该函数会触发,但是如果我在输入字段中键入内容,我不希望该函数触发,有没有办法做到这一点?

 window.addEventListener("onkeydown", keyDown, true); window.addEventListener("keydown", keyDown); function keyDown() { var e = window.event; switch (e.keyCode) { case 72: // Key H test(); break; } } function test() { document.getElementById('Codefield').value = Math.random().toString(36).substring(2, 15); } 
 <input id="Codefield" value="" type="text"> <input id="Codefield2" value="Stop test function keydown or keydown if typeing here" type="text"> 

If you add event listeners to window , all your inputs will fire the function. 如果将事件侦听器添加到window ,则所有输入将触发该函数。 Add the event listener only where you need it. 仅在需要的地方添加事件监听器。

document.getElementById('Codefield').addEventListener("onkeydown", keyDown, true);

Another technique would be to check the e.target from inside the trigger function and ignore the code if it is from an input you don't want to handle. 另一种技术是从触发器函数内部检查e.target ,如果它来自您不想处理的输入,则忽略该代码。

You can check whether the current element is an input element. 您可以检查当前元素是否为输入元素。

function keyDown(e) {
  if (this.tagName == 'INPUT') {
    e.stopPropagation();
    return;
  }
  switch (e.keyCode) {
    case 72: // Key H
      test();
      break;
  }
}

Also, don't use window.event . 另外,不要使用window.event That's non-standard and won't work in Firefox. 这是非标准的,无法在Firefox中使用。 The event is the first argument to the event listener. 事件是事件侦听器的第一个参数。

Maybe you should use a focus selector (from jQuery): 也许您应该使用focus选择器(来自jQuery):

if($("#Codefield2:focus")) {
    thisInput = true;
}

Then add an if statement at the start of your function, and check if thisInput is true or not. 然后在函数的开头添加if语句,并检查thisInput是否为true。

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

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