当前位置: 动力学知识库 > 问答 > 编程问答 >

events - Key Up isn't working Javascript

问题描述:

I have no idea how this works. I am trying to learn key events. I got keydown to work, but key up just won't work. Any help appreciated.

 window.onload = function(){

window.addEventListener('keyup' , loopit1 ); // this doesn't work.

/*window.addEventListener('keydown' , loopit2 );*/ // this works. That's why it's commented out.

function loopit1(e){

if(e.ctrlKey){

alert("Key Up!");

}

//This doesn't work.

}

/*function loopit2(e){

if(e.ctrlKey){

alert("Key Down!");

}

}*// This Works. That's why it's commented out.

}

网友答案:

if you log out the event object, you'll see that e.ctrlKey = true on the keydown event, but e.ctrlKey = false on the keyup event.

Why you ask?

I can't really refer you to a source or any facts, but my thesis is like this:

The e.ctrlKey property is there for you to check if the ctrl key is pressed down while you click a button. As you'll find out by checking it out, the event object has a lot of these properties for you to check. This way, it's easier to check if the user is clicking ctrl+s or alt+f7 or whatever.

The reason the e.ctrlKey always is false is probably because is never needed. Weird perhaps, but it doesn't really make sense to have it set in the first place, given my argument above.

A solution to your problem is to check the keyCode property instead - the key for ctrl is 17.

function loopit1(e){
    if(e.keyCode === 17){
        alert("Key Up!");
    }
}

Hope this helps!

网友答案:

It does work. The ctrlKey property indicates whether the Ctrl key is pressed at the time that the event fires. Therefore, it won't fire if the Ctrl key was the key that just came up, since the keyup event fires temporally after the Ctrl key comes up. If the Ctrl key is down while another key comes up, then e.ctrlKey will be true.

However, it needs to be a key that doesn't cause a browser action that takes away focus from the document -- if I bring the T key up while holding down Ctrl, the browser will move to a new tab before the event can happen. Try out Ctrl+Alt: while holding down the Ctrl key, press and release Alt.

If you want to test whether the Ctrl key itself has been lifted, you should check e.keyCode for the value 17. However, e.keyCode is deprecated, and should be replaced with e.key in the future. However, e.key is not yet widely implemented, so you must use keyCode for the time being.

分享给朋友:
您可能感兴趣的文章:
随机阅读: