触发键盘事件,webkit键盘事件不会触发

时间:2010-06-20 15:39:32

标签: javascript javascript-events keyboard webkit keypress

我有javaScript代码,它会监听按下的“return”键,
适用于除webkit浏览器之外的所有浏览器

我最近了解了webkits changes to keyboard event handling 我找不到合适的解决方案 in this detailed explanation

这是code

function addEventHandler(node,type,fn){
   if(typeof window.event !== "undefined"){
            /* Internet Explorer way */
            node.attachEvent( "on" + type, fn );
   } else {
           /* FF & Other Browsers */
           node.addEventListener( type, fn,false );
   }
} 


function detectSubmit(){
    searchTextInput = document.getElementById("txtSearch")
    addEventHandler(searchTextInput,"keydown",triggerSearch);
}

function triggerSearch(e){
  //getting the character that was pressed cross browser. 
     var key = e.keycode ? e.keycode : e.which;
  //detect if the return key was pressed. 
    if(key==13){
      alert("return clicked");
    }
}

   addEventHandler(window,"load",detectSubmit);

1 个答案:

答案 0 :(得分:2)

最明显的是下一行的简单拼写错误:

var key = e.keycode ? e.keycode : e.which;

应该是keyCode而不是keycode

除此之外,addEventHandler功能存在问题。我建议如下:

function addEventHandler(node,type,fn){
    if (typeof node.addEventListener !== "undefined"){
        /* DOM-compliant method */
        node.addEventListener( type, fn,false );
    } else if (typeof node.attachEvent !== "undefined") {
        /* IE */
        node.attachEvent( "on" + type, fn );
    }
}

两件事:首先,最好直接检查attachEvent,而不是从window.event的存在推断它的存在。事实上,window.event存在于Safari和Chrome中,但不存在(我认为)attachEvent,因此狡猾的推断会阻止您的代码正常工作。

其次,最好首先检查DOM标准addEventListener,然后将其用于存在而不是attachEvent的位置。例如,Opera有两种,但只有addEventListener是标准化的。