2012-02-21 110 views
31

我在這裏看到一些類似的問題(如JavaScript: Check if CTRL button was pressed),但我的問題實際上是事件觸發。我的js代碼:javascript - 檢測按鍵或按下按鍵,按鍵事件不會觸發

// Listen to keyboard. 
    window.onkeypress = listenToTheKey; 
    window.onkeyup = listenToKeyUp; 

    /* 
     Gets the key pressed and send a request to the associated function 
     @input key 
    */ 
    function listenToTheKey(e) 
    { 
     if (editFlag == 0) 
     { 
      // If delete key is pressed calls delete 
      if (e.keyCode == 46) 
       deleteNode(); 

      // If insert key is pressed calls add blank 
      if (e.keyCode == 45) 
       createBlank(); 

      if (e.keyCode == 17) 
       ctrlFlag = 1; 
     } 
    } 

事件引發了除CTRL任何其他鍵。
我還需要觸發它爲ctrl
我不能使用jQuery/prototype/whatever,所以這些解決方案是不可接受的。

所以...我怎麼能檢測到ctrl

+1

不是這樣的:if(e.ctrlKey){....} work ..? – 2012-02-21 09:26:01

回答

15

你的事件有一個名爲ctrlKey屬性。你可以檢查這個看看是否按下了鍵。請參閱下面的代碼片段,以獲得更多控制權,如按鍵

function detectspecialkeys(e){ 
    var evtobj=window.event? event : e 
    if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey) 
     alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys") 
} 
document.onkeypress=detectspecialkeys 
7

使用onkeydown而不是onkeypress可能會有所幫助。

http://www.w3schools.com/jsref/event_onkeypress.asp

注:onkeypress事件事件不會解僱所有鍵(例如ALT,CTRL,SHIFT ,ESC)在所有瀏覽器。要僅檢測用戶是否按下了某個鍵,請使用onkeydown事件,因爲它適用於所有鍵的 。