如何处理ENTER按键以触发onBlur()事件?

时间:2011-07-01 12:49:51

标签: javascript ipad

我有一个iPad webapp,在某些时候有一个很大的<form>。其中的每个输入都具有控制值的功能,包括keyUp和Blur事件。

事实是,如果用户在键入时意外点击“GO”按钮(被视为“输入”按键),则提交表单。我想拦截这个comportment并触发focus元素的onBlur()事件。

现在我有了这个:

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
  }
}

你们对此有什么建议/想法/改进吗?

Nota bene:必须至少有一个输入专注于iPad的键盘弹出。

2 个答案:

答案 0 :(得分:2)

发现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;
}

答案 1 :(得分:0)

这不适用于所有浏览器。

  

document.addEventListener( “的keydown”,logPressedKeys,FALSE);

像这样使用:

  document.onkeydown = function (e) {
            alert(e.keyCode); 

        }
相关问题