简体   繁体   English

如何在JavaScript中释放键时进行测试

[英]How would I test for when a key is released in JavaScript

I would like to have a variable become true when I press a key, and become false when it is released. 我想让一个变量在我按下一个键时变为true,而在释放它时变为false。 I have a function that sets the var to true when the key is pressed, but I need to have a function called when a key is released as well to reset the var to false. 我有一个函数,可以在按下键时将var设置为true,但是我还需要有一个在释放键时将var重置为false的函数。

<input onkeydown="doX();" onkeyup="doY();" type="text">

<script type="text/javascript">     
   var flag = false;   
   function doX(){
      flag = true;        
   }

   function doY(){
     flag = false;    
   }
</script>

Expl: 说明:

There are two important keyboard events can help here. 这里有两个重要的键盘事件可以提供帮助。

  1. keydown (will be fired when a key is pressed) keydown(按下键时将触发)
  2. keyup (will be fired when a key is released) keyup(释放键时将触发)

call the doX function on keydown event and call doY function on keyup event!! 在keydown事件上调用doX函数,在keyup事件上调用doY函数!

Code # 2: 代码2:

<script type="text/javascript">
    var input = document.getElementById("test");
    var flag;       
    input.onkeydown = function(){
        flag = false;
    }

    input.onkeyup = function(){
        flag = true;
    }
</script> 

As, you asked to identify 'SPACE BAR', I have added the code here: 正如您所要求的,以识别“空格键”,我在此处添加了代码:

<script type="text/javascript">
    var input = document.getElementById("test");
    var flag;       
    input.onkeydown = function(e){
        var char = e.keyCode; //32 is for 'SPACE BAR'           
        flag = false;
    };

    input.onkeyup = function(e){
        var char = e.keyCode; //32 is for 'SPACE BAR'           
        flag = true;
    };
</script>

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

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