1、瀏覽器的按鍵事件
瀏覽器有3種按鍵事件——keydown,keypress和keyup,分別對應(yīng)onkeydown、onkeypress和onkeyup3個事件句柄。
一個典型的按鍵會產(chǎn)生所有這三種事件,依次是keydown-->keypress-->keyup。
例如:下面代碼每當(dāng)按下鍵盤按鍵時,經(jīng)歷的三種事件分別在console控制臺中依次打印出所經(jīng)歷事件名稱 keydown、keypress、keyup。
<input type="text" id="text">
<script>
document.getElementById("text").onkeypress = function() {
console.log("keypress");
};
document.getElementById("text").onkeyup = function() {
console.log("keyup");
};
document.getElementById("text").onkeydown = function() {
console.log("keydown");
};
</script>
*(可選) 為了調(diào)試顯示效果更佳,可配合如下樣式 *
<!--(可選) 為了調(diào)試顯示效果更佳,可配合如下樣式 -->
<style type="text/css">
input {
height: 80px;
padding: 20px;
font-size: 50px;
letter-spacing: 0.5em;
}
</style>
2、瀏覽器的兼容性
(1)FireFox、Opera、Chrome
事件對應(yīng)的函數(shù)有一個隱藏的變量e,表示發(fā)生事件。
e有一個屬性e.which指示哪個鍵被按下,給出該鍵的索引值(按鍵碼)。
靜態(tài)函數(shù)String.fromCharCode()可以把索引值(按鍵碼)轉(zhuǎn)化成該鍵對應(yīng)的的字符。
<input type="text" id="text">
<script>
document.getElementById("text").onkeypress = function(e) {
console.log("按鍵碼: " + e.which + " 字符: " + String.fromCharCode(e.which));
};
</script>
FireFox、Opera、Chrome中輸入:a
輸出:按鍵碼:97 字符:a
(2)IE
IE不需要e變量,window.event表示發(fā)生事件。
window.event有一個屬性window.event.keyCode指示哪個鍵被按下,給出該鍵的索引值(按鍵碼)。
靜態(tài)函數(shù)String.fromCharCode()可以把索引值(按鍵碼)轉(zhuǎn)化成該鍵對應(yīng)的的字符。
<input type="text" id="text">
<script>
document.getElementById("text").onkeypress = function() {
console.log("按鍵碼: " + window.event.keyCode + " 字符: " + String.fromCharCode(window.event.keyCode));
};
</script>
IE中輸入:a
輸出:按鍵碼:97 字符:a
3、判斷瀏覽器類型
利用navigator對象的appName屬性。
IE:navigator.appName=="Microsoft Internet Explorer"
FireFox、Opera、Chrome:navigator.appName=="Netscape"
<input type="text" id="text">
<script>
document.getElementById("text").onkeypress = function(e) {
if (navigator.appName == "Microsoft Internet Explorer")
console.log("按鍵碼: " + window.event.keyCode + " 字符: " + String.fromCharCode(window.event.keyCode));
else if (navigator.appName == "Netscape")
console.log("按鍵碼: " + e.which + " 字符: " + String.fromCharCode(e.which));
};
</script>
IE、FireFox、Opera、Chrome中輸入:a
輸出:按鍵碼:97 字符:a
簡化的寫法:
<input type="text" id="text">
<script>
document.getElementById("text").onkeypress = function(e) {
e = e || window.event; // window.event 代表IE瀏覽器
// e.keyCode e.which e.charCode 三個任何一個為真,則后面不再比對,并將其值賦值給key
key = e.keyCode || e.which || e.charCode;
console.log("按鍵碼: " + key + " 字符: " + String.fromCharCode(key));
};
</script>

說明:IE只有keyCode屬性,F(xiàn)ireFox中有which和charCode屬性,Opera中有keyCode和which屬性,Chrome中有keyCode、which和charCode屬性。