admin管理员组

文章数量:1410737

For some reason this script isn't working in Firefox:

document.onkeydown=function keypress(e) {
    if (e.keyCode == 27) {
        window.location = "/edit"
    };
};

It works fine in Chrome, but for some reason it's not working in Firefox.

Basically, what it does is load the /edit page when you press the escape key.

For some reason this script isn't working in Firefox:

document.onkeydown=function keypress(e) {
    if (e.keyCode == 27) {
        window.location = "/edit"
    };
};

It works fine in Chrome, but for some reason it's not working in Firefox.

Basically, what it does is load the /edit page when you press the escape key.

Share Improve this question edited Sep 28, 2011 at 9:59 akjoshi 15.8k13 gold badges106 silver badges122 bronze badges asked Aug 28, 2011 at 1:57 JacobTheDevJacobTheDev 18.6k29 gold badges102 silver badges161 bronze badges 2
  • Works for me in FF5: jsfiddle/Tm2PZ – Mrchief Commented Aug 28, 2011 at 2:32
  • trying running console.log(e). Check the output to check if something is occuring. – uadnal Commented Aug 28, 2011 at 2:40
Add a ment  | 

3 Answers 3

Reset to default 7

use:

document.onkeydown=function keypress(e) {
  e=(e||window.event);  
    if (e.keyCode == 27) {
        try{e.preventDefault();}//Non-IE
        catch(x){e.returnValue=false;}//IE
        window.location = "/edit";
    };
}

The default-action for ESC is to stop loading the page,
so you must prevent from this behaviour, otherwise you cannot change the location.

Fiddle: http://jsfiddle/doktormolle/CsqgE/ (Click into the result-frame first before using ESC)

But however, you really should use another key.
A user expects that the loading of the current page stops if he uses ESC , nothing else.

The event handler is working for me: http://jsfiddle/Tm2PZ/

I suspect the lcoation you're setting is not valid.

Try setting window.location.href instead.

if you don't use 'Escape keyup or Escape keydown'
for other things in your code, you can use 'keyup' to replace keypress**

 document.body.addEventListener( 'keyup', function (e) {
        e=(e||window.event);
        if (e.key == "Escape") {
            console.log('escape is pressed');
        }    
    },false ); 

e.keyCode is depreciate, use e.key, add "console.log(e.key)"
in your listener if you want to get key name
it is better, because it adapts to the keyboard which does not have the same position and e.keyCode does not adapt

本文标签: javascriptEsc key not getting recognized in FirefoxStack Overflow