发生keypress事件意味着按下的键会影响到屏幕中文本的显示。在所有浏览器中,按下能够插入或删除字符的键都会触发keypress事件,按下其他键能否触发此事件因浏览器而异。IE9、Firefox、Chrome和Safari的event对象都支持一个charCode属性,这个属性只有在发生keypress事件时才包含值、而且这个值是按下的那个键所代表字符的ASCII编码。此时的keyCode通常等于0或者也可能等于所按键的键码。IE8及之前版本和Opera则是在keyCode中保存字符的ASCII编码。要想以跨浏览器的方式取得字符编码,必须首先检测charCode属性是否可用,如果不可用则使用keyCode。
<script type="text/javascript"> (function(){ function getCharCode(event){ if(typeof event.charCode=="number"){ return event.charCode; }else{ return event.keyCode; } } var keyInput=document.querySelector("input[name='key']"); var keyCode=document.querySelector("input[name='keyCode']"); keyInput.style.cssText=keyCode.style.cssText="background-color:white;border-color:#000;border-style:solid;border-width:1px;box-sizing:border-box;display:block;border-radius:5px;padding:8px;width:100%;box-shadow:1px 1px 2px #ccc inset;"; if(keyInput.addEventListener){ keyInput.addEventListener("keypress",function(event){ keyCode.value=keyCode.value+" "+getCharCode(event)+"("+String.fromCharCode(getCharCode(event))+")"; },false); }else if(keyInput.attachEvent){ keyInput.attachEvent("onkeypress",function(event){ keyCode.value=keyCode.value+" "+getCharCode(event)+"("+String.fromCharCode(getCharCode(event))+")"; }); } })(); </script>
这个方法首先检测charCode属性是否包含数值(在不支持这个属性的浏览器中,值为undefined),如果是则返回该值。否则就返回keyCode属性值。在取得了字符编码之后,就可以使用String.fromCharCode()将其转换成实际的字符。