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.
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.net/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.net/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 composition and e.keyCode does not adapt
精彩评论