javascript 如何处理按下 ENTER 键以触发 onBlur() 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6548176/
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
How to handle the ENTER keypressed to trigger an onBlur() event?
提问by monsieur_h
I have an iPad webapp with a big <form>
at some point. Every input in it has functions controlling the values, both on keyUp and Blur events.
我有一个 iPad 网络应用程序<form>
,有时会很大。其中的每个输入都有控制值的函数,包括 keyUp 和 Blur 事件。
Thing is, if the user accidentaly hits the "GO" button while typing (considered as an "enter" keypress), the form is submitted. I would like to intercept this comportment and trigger the onBlur() event of the focused element instead.
事实是,如果用户在键入时不小心点击了“GO”按钮(被视为“输入”按键),则提交表单。我想拦截这个comportment并触发焦点元素的onBlur()事件。
For now I have this:
现在我有这个:
load(){
document.addEventListener("keydown",logPressedKeys,false);
}
/**
* logs the keys hit in the console, will eventually trigger my onBlur event
*/
function logPressedKeys(e) {
console.log(e.keyCode);
if (e.keyCode==13) {
console.log('Enter spotted: prevent!');
e.preventDefault();//Shall prevent submitting
return false;//Hoping it prevents default if above fails
}
}
Do you guys have any advice/idea/improvement about that?
你们对此有什么建议/想法/改进吗?
Nota bene: There has to be at least one input focused for the iPad's keyboard to pop.
注意:必须至少有一个输入焦点才能让 iPad 的键盘弹出。
采纳答案by monsieur_h
Found out that document.activeElement works out in iPad's Safari.
发现 document.activeElement 在 iPad 的 Safari 中有效。
function logPressedKeys(e) {
console.log(e.keyCode);
if (e.keyCode==13) {
e.preventDefault();
console.log('Enter spotted: prevent!');
temp=document.activeElement;
//console.log(temp);
temp.onblur();
return false;
}
return true;
}
回答by marko
This will not work in every browser.
这不适用于所有浏览器。
document.addEventListener("keydown",logPressedKeys,false);
document.addEventListener("keydown",logPressedKeys,false);
Use like this:
像这样使用:
document.onkeydown = function (e) {
alert(e.keyCode);
}