Javascript e.keyCode 无法在 IE 中捕获 Backspace/Del
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4084715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript e.keyCode doesn't catch Backspace/Del in IE
提问by indranama
I'm trying to catch the pressing event of Backspace and Delete keys using javascript/jQuery with this kind of code.
我正在尝试使用带有这种代码的 javascript/jQuery 来捕获 Backspace 和 Delete 键的按下事件。
$("textarea[name=txt]").keypress(function(e){
var keycode = e.keyCode ? e.keyCode : e.which;
if(keycode == 8){ // backspace
// do somethiing
alert(keycode);
}
if(keycode == 46){ // delete
// do somethiing
alert(keycode);
}
});
These lines of code works perfectly in Firefox (3.6.12). That means the alert is popped up when Backspace or Delete is pressed. But this is not working in Internet Explorer (8)
这些代码行在 Firefox (3.6.12) 中完美运行。这意味着当按下 Backspace 或 Delete 时会弹出警报。但这在 Internet Explorer (8) 中不起作用
Can anyone suggest me a different way to catch these key press events in Internet Explorer?
任何人都可以建议我在 Internet Explorer 中捕获这些按键事件的不同方法吗?
回答by gblazex
If you want to support IE and you use special keys (like delete
and backspace
) I suggest using keydown
/keyup
instead.
如果您想支持 IE 并使用特殊键(如delete
和backspace
),我建议使用keydown
/keyup
代替。
Special keys
Explorer doesn't fire the keypressevent for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.
特殊键
资源管理器不会触发删除、结束、输入、转义、功能键、主页、插入、pageUp/Down 和 tab的按键事件。
如果您需要检测这些键,请帮自己一个忙并搜索它们的 keyCode onkeydown/up,并忽略 onkeypress 和 charCode。
You can read more on cross browser issues of Detecting keystrokes(Quirksmode).
您可以阅读有关Detecting keystrokes (Quirksmode) 的跨浏览器问题的更多信息。
回答by Rajat Bhatia
Key Code for Backspace will take the value = 83if we already have a few characters in a Text Box .
如果 Text Box 中已经有几个字符,则Backspace 的键代码将取值 = 83 。
The Key Code will be = 8if there are NO Characters in the Text Box and we are trying to Hit Backspace.
如果文本框中没有字符并且我们正在尝试按退格键,则密钥代码将为 = 8 。