1、瀏覽器的按鍵事件
瀏覽器有3種按鍵事件——keydown,keypress和keyup,分別對應onkeydown、onkeypress和onkeyup3個事件句柄。
一個典型的按鍵會產生所有這三種事件,依次是keydown-->keypress-->keyup。
1 <input type="text" id="text"> 2 <script> 3 document.getElementById("text").onkeypress = function() { 4 console.log("keypress"); 5 }; 6 document.getElementById("text").onkeyup = function() { 7 console.log("keyup"); 8 }; 9 document.getElementById("text").onkeydown = function() { 10 console.log("keydown"); 11 }; 12 </script>
控制台輸出:
keydown
keypress
keyup
2、瀏覽器的兼容性
(1)FireFox、Opera、Chrome
事件對應的函數有一個隱藏的變量e,表示發生事件。
e有一個屬性e.which指示哪個鍵被按下,給出該鍵的索引值(按鍵碼)。
靜態函數String.fromCharCode()可以把索引值(按鍵碼)轉化成該鍵對應的的字符。
eg:
1 <input type="text" id="text"> 2 <script> 3 document.getElementById("text").onkeypress = function(e) { 4 alert("按鍵碼: " + e.which + " 字符: " + String.fromCharCode(e.which)); 5 }; 6 </script>
FireFox、Opera、Chrome中輸入:a
輸出:按鍵碼:97 字符:a
(2)IE
IE不需要e變量,window.event表示發生事件。
window.event有一個屬性window.event.keyCode指示哪個鍵被按下,給出該鍵的索引值(按鍵碼)。
靜態函數String.fromCharCode()可以把索引值(按鍵碼)轉化成該鍵對應的的字符。
eg:
1 <input type="text" id="text"> 2 <script> 3 document.getElementById("text").onkeypress = function() { 4 alert("按鍵碼: " + window.event.keyCode + " 字符: " + String.fromCharCode(window.event.keyCode)); 5 }; 6 </script>
IE中輸入:a
輸出:按鍵碼:97 字符:a
3、判斷瀏覽器類型
利用navigator對象的appName屬性。
IE:navigator.appName=="Microsoft Internet Explorer"
FireFox、Opera、Chrome:navigator.appName=="Netscape"
eg:
1 <input type="text" id="text"> 2 <script> 3 document.getElementById("text").onkeypress = function(e) { 4 if (navigator.appName == "Microsoft Internet Explorer") 5 alert("按鍵碼: " + window.event.keyCode + " 字符: " + String.fromCharCode(window.event.keyCode)); 6 else if (navigator.appName == "Netscape") 7 alert("按鍵碼: " + e.which + " 字符: " + String.fromCharCode(e.which)); 8 }; 9 </script>
IE、FireFox、Opera、Chrome中輸入:a
輸出:按鍵碼:97 字符:a
簡化的寫法:
1 <input type="text" id="text"> 2 <script> 3 document.getElementById("text").onkeypress = function(e) { 4 e = e || window.event; 5 key = e.keyCode || e.which || e.charCode; 6 alert("按鍵碼: " + key + " 字符: " + String.fromCharCode(key)); 7 }; 8 </script>
說明:IE只有keyCode屬性,FireFox中有which和charCode屬性,Opera中有keyCode和which屬性,Chrome中有keyCode、which和charCode屬性。