element onkeydown keycode javascript

前端 未结 4 671
傲寒
傲寒 2021-01-14 09:36

I am using this code snippet to add KeyDown event handler to any element in the html form

for(var i=0;i

        
相关标签:
4条回答
  • 2021-01-14 10:04

    I used this:

    function check(){
     if (event.keyCode == 32){
      alert("Space is pressed");
     }
    }
    

    and in my body tag: onKeyPress="check()"

    0 讨论(0)
  • 2021-01-14 10:10

    This is the code I use for this problem. It works in every browser.

    //handle "keypress" for all "real characters"     
    if (event.type == "keydown") {
        //some browsers support evt.charCode, some only evt.keyCode
       if (event.charCode) {
          var charCode = event.charCode;
       }
       else {
          var charCode = event.keyCode;
       }
    }
    
    0 讨论(0)
  • 2021-01-14 10:10

    It is keyCode, not KeyCode.

    0 讨论(0)
  • 2021-01-14 10:16

    For detecting Enter, you could use the following code, which will work in all mainstream browsers. It uses the keypress event rather than keydown because Enter produces a printable character:

    ele[i].onkeypress = function(evt) {
        evt = evt || window.event;
        var charCode = evt.keyCode || evt.which;
        if (charCode == 13) {
            alert("Enter");
            // Do stuff here
        }
    };
    
    0 讨论(0)
提交回复
热议问题