listen to 'CTRL+N' with javascript

旧巷老猫 提交于 2021-01-05 07:14:49

问题


I am trying to bind the 'CTRL+N' key combination, like this:

var ctrlPressed = false;
    var nCode = 78;
    var ctrlCode = 224;
    var cmdCode = 17;
    document.addEventListener ("keydown", function(e){
        if( e.keyCode == ctrlCode || e.keyCode == cmdCode){
            ctrlPressed = true;
        }else{
            ctrlPressed = false;
        }
        console.log(e.keyCode);
    });
    document.addEventListener ("keyup", function(e){
        if(ctrlPressed && e.keyCode == nCode){
             e.preventDefault();
            nou_element(parent);
            return;
        }
    });

Please note: jQuery isn't avaliable

The thing is that the e.preventDefault() doesn't seem to override the create window functionality built into the bowser

how can I bypass?


回答1:


You code has some problems:

  • Not all browsers allow you to prevent default keyboard actions (like Chromium 30)

  • To prevent them on the others (like Firefox or IE8), you must prevent keydown event instead of keyup one, because then it's too late.

  • To check if Ctrl key is pressed, use e.ctrlKey

Demo (for Firefox)

document.addEventListener("keydown", function(e){
    if(e.ctrlKey && e.keyCode == /*key code*/) {
        e.preventDefault();
        /* Do whatever */
    }
});

Demo (for Firefox & IE8)

document.onkeydown =  function(e){
    e = e || window.event;
    if(e.ctrlKey && e.keyCode == nCode) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
        /* Do whatever */
        return false;
    }
};


来源:https://stackoverflow.com/questions/20444085/listen-to-ctrln-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!