Event.KeyCode,Event.Which

來源:互聯網
上載者:User

今天去修改一個老系統的時候,解決了一個按鈕觸發在不同瀏覽器上相容的問題。就順手差了一些資料,不要知其然不知其所以然。

先介紹幾個簡單的

KeyDown事件:

當瀏覽器讀到這個語句時,無論按下鍵盤上的哪個鍵,都將呼叫KeyDown()函數

function keyDown(){}document.onkeydown = keyDown;

IE下讀取鍵盤按鍵

keycode = event.keyCode;//String.fromCharCode(event.keyCode)//索引轉換。

FF下讀取鍵盤按鍵

keycode = e.which;String.fromCharCode(e.which);// 索引轉換。

 so可以看到不同瀏覽器下對鍵盤按鈕的讀取的方式不同,

ie是enent.keyCode,而FF是event.which.

------------------------------------------------------------------------華麗的分割線------------------------------------------------------------------------------------------------------------------

這裡.我的問題已經解決,判斷一下瀏覽器就再執行不同的方法就可以了。

一般青年解決方案

通過navigator的appName判斷.

function keyUp(e) {    if(navigator.appName == "Microsoft Internet Explorer")   {     var keycode = event.keyCode;      var realkey = String.fromCharCode(event.keyCode);    }else   {      var keycode = e.which;        var realkey = String.fromCharCode(e.which);    }   alert("按鍵碼: " + keycode + " 字元: " + realkey); }document.onkeyup = keyUp;

 文藝青年解決方案

function keyUp(e) {            var currKey = 0, e = e || event;            currKey = e.keyCode || e.which || e.charCode;            var keyName = String.fromCharCode(currKey);            alert("按鍵碼: " + currKey + " 字元: " + keyName);        }        document.onkeyup= keyUp;

 解釋一下

e=e||event

js中這句代碼的意思是,如果在FireFox或Opera中,隱藏的變數e是存在的,那麼e||event返回e,如果在IE中,隱藏變數e是不存在,則返回event。

currKey=e.keyCode||e.which||e.charCode;

這句是為了相容瀏覽器按鍵事件對象的按鍵碼屬性(詳見第三部分), 如IE中,只有keyCode屬性,而FireFox中有which和charCode屬性,Opera中有keyCode和which屬性等。

-----------------------------------------------------------------我又來分割了----------------------------------------------------------------------


問題已經解決,很基礎的問題,我順手用jquery試了一下

網上找了一段代碼是這樣的。

<script language="javascript">       $(function() {           $("#input1").keydown(function (event) {               $("#div1").html("Key: " + event.keyCode);           });               });         </script>

 



 

 

 

 

 

 

 

 

 

這是ie中的效果  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.