2010-08-05 33 views

回答

1

keypress事件是您想要的,因爲這是您可以收集有關輸入字符的信息的唯一事件。在報價的情況下,您可以自己處理按鍵。這裏沒有介紹用CSS類插入<span>的代碼。如果您需要幫助,我會建議詢問另一個問題,或者閱讀DOM Ranges,TextRanges和選擇in IEother browsers的一些文檔。

function handleKeypress(evt) { 
    evt = evt || window.event; 
    var charCode = evt.which || evt.keyCode; 
    var charStr = String.fromCharCode(charCode); 
    if (charStr == "'" || charStr == '"') { 
     // Code to insert quote character followed by <span> with CSS class 
     // goes here. 

     // Prevent the default action 
     if (evt.preventDefault) { 
      evt.preventDefault(); 
     } else { 
      evt.returnValue = false; 
     } 
    } 
} 

var div = document.getElementById("your_div"); 
if (div.addEventListener) { 
    div.addEventListener("keypress", handleKeypress, false); 
} else if (div.attachEvent) { 
    div.attachEvent("onkeypress", handleKeypress); 
} 
0

我不確定我完全理解你正在嘗試做什麼,但似乎你希望將用戶輸入捕獲到帶有contentEditable屬性的div中。如果我使用MootoolsFirebug我會用下面開始::

$('idOfEditableDiv').addEvent('keydown', function(event) { 
    console.log(event.key); 
    }); 

,將打印到Firebug控制檯是內容編輯DIV中按下任意鍵。所以如果我按下'a'鍵,'a'會被打印出來。如果您希望捕獲不具有明顯價值的輸入,例如Caps Lock鍵,這會非常有用。記錄整個事件console.log(event)可以給你更多有用的信息。

當你已經確定你想捕捉(比如A和B鍵)哪個鍵,然後執行以下操作:

$('idOfEditableDiv').addEvent('keydown', function(event) { 
    if(event.key == 'a' || event.key == 'b') { 
     //do stuff here if the a or b key was pressed 
     } 
    }); 

有時候,如果按和其他的關鍵,你可能想要做的東西如果b鍵被按下的話。在這種情況下,請執行下列操作:

$('idOfEditableDiv').addEvent('keydown', function(event) { 
    if(event.key == 'a') { 
     //do stuff here if the a key was pressed 
     } 
    else if(event.key == 'b') { 
     //do stuff here if the b key was pressed 
     } 
    }); 

如果你不熟悉Mootools的,你需要換你的所有Mootools的代碼在domready中的事件是這樣的:

window.addEvent('domready', function() { 
    $('idOfEditableDiv').addEvent('keydown', function(event) { 
     if(event.key == 'a') { 
      //do stuff here if the a key was pressed 
      } 
     else if(event.key == 'b') { 
      //do stuff here if the b key was pressed 
      } 
     }); 
    }); 

More information about Mootools Events