试图理解javascript的关键事件处理

时间:2010-08-26 18:34:17

标签: javascript

我想知道为什么this page的源使用所有这些if-else来添加事件监听器:

if (document.addEventListener)
{
   document.addEventListener("keydown",keydown,false);
   document.addEventListener("keypress",keypress,false);
   document.addEventListener("keyup",keyup,false);
   document.addEventListener("textInput",textinput,false);
}
else if (document.attachEvent)
{
   document.attachEvent("onkeydown", keydown);
   document.attachEvent("onkeypress", keypress);
   document.attachEvent("onkeyup", keyup);
   document.attachEvent("ontextInput", textinput);
}
else
{
   document.onkeydown= keydown;
   document.onkeypress= keypress;
   document.onkeyup= keyup;
   document.ontextinput= textinput;   // probably doesn't work
}

是否与大多数浏览器兼容?

1 个答案:

答案 0 :(得分:1)

if (document.addEventListener) // DOM spec that all browsers should follow

else if (document.attachEvent) // but unfortunately IE does not follow them    

else // and there may be other older browsers that follow neither