js兼容firefox和ie的ctrl+enter事件捕获

来源:互联网 发布:腾讯 大数据事业部 编辑:程序博客网 时间:2024/05/18 00:00

想用JavaScript写个捕获ctrl+enter事件的函数,原本是简单的判断event.ctrlKey&&按键的keycode为13就可以了,却发现该函数在firefox下可以用用,在ie下却挂了,最后查找ie下的ctrl+enter应该判断按键码为10.例子如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

   <head>

   <title>Js Ctrl And Enter Event Caputure</title>

     <style>

     *{margin:0;padding:0;line-height:18px;}

     </style>

     </head>

<body>

     <div id="display"style="margin:40px auto;width:400px;height:200px;">

     </div>

     <div style="margin:0 auto;width:400px;text-align:center;">

         <textarea onkeypress="capture(event,this)"style="width:400px;height:200px;line-height:18px;"></textarea>

     <div>

</body>

</html>

<script language='javascript'>

     window.$= function(id){returndocument.getElementById(id);}

     function capture(event,o)

     {

         var keynum;

         if(window.event)

         {

              keynum=event.keyCode;

         }

         else

         {

              keynum=event.which;

         }

         event= event || window.event;

         if(event.ctrlKey&&(keynum==13||keynum==10))

         {

              $('display').innerHTML += '<p>'+ o.value + '</p>';

              o.value='';

         }

     }

</script>