admin管理员组

文章数量:1327676

I'm trying to embed some keybindings in my webapp, and I'm having hard times with Opera. I have this code:

window.onkeydown = function(e){
  var key = e.keyCode ? e.keyCode : e.charCode ? e.charCode : false;
  if (e.ctrlKey && key === 84) {
    alert("foo");
    e.preventDefault();
    // return false;
  }
}

It works like a charm in Firefox and Chrome, but Opera still opens new tab. Same happens with return false;.

My info: Opera/9.80 (X11; Linux i686; U; en) Presto/2.7.62 Version/11.00

I'm trying to embed some keybindings in my webapp, and I'm having hard times with Opera. I have this code:

window.onkeydown = function(e){
  var key = e.keyCode ? e.keyCode : e.charCode ? e.charCode : false;
  if (e.ctrlKey && key === 84) {
    alert("foo");
    e.preventDefault();
    // return false;
  }
}

It works like a charm in Firefox and Chrome, but Opera still opens new tab. Same happens with return false;.

My info: Opera/9.80 (X11; Linux i686; U; en) Presto/2.7.62 Version/11.00

Share Improve this question asked Jan 23, 2011 at 12:47 aL3xaaL3xa 36.1k18 gold badges81 silver badges112 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Opera doesn't support preventDefault on keydown, only on keypress.

As you can see in this example, you should bind a separate keypress handler for Opera (adapted to your situation):

var cancelKeypress = false;

document.onkeydown = function(evt) {
    evt = evt || window.event;
    cancelKeypress = (evt.ctrlKey && evt.keyCode == 84);
    if (cancelKeypress) {
        return false;
    }
};

/* For Opera */
document.onkeypress = function(evt) {
    if (cancelKeypress) {
        return false;
    }
};

本文标签: javascriptOpera preventDefault() on keydown eventStack Overflow