只要您的文本字段具有焦點,除了您的keyup或keydown偵聽器添加到它之外,您按下的任何數字鍵都將被添加到它。也許你應該從keydown上的文本字段中取消焦點,如果你按下的鍵是向下鍵並且在keyup事件觸發後再次添加焦點。
/* Keep track of the down key. */
var down=false;
/* Get the input text field. */
var input=document.getElementById("input");
input.addEventListener("keydown",keyDown);
input.addEventListener("keyup",keyUp);
/* Give focus to input. I'm not sure if this is the right way to do it, I haven't tested this code, but I know there's a way to give focus to elements and it sort of looks like this. */
input.focus();
function keyDown(event_){
switch(event_.keyCode){
case 40:
/* Once again, not sure how to unfocus, but I know you can. */
input.unfocus();
down=true;
break;
}
}
function keyUp(event_){
switch(event_.keyCode){
case 40:
/* Give focus back to input after the keyup event has fired. */
input.focus();
down=false;
break;
}
if (down){
input.value+=//The subscript version of whatever key you pressed.
}
}
再次,我只想說,這個代碼沒有經過測試,我不知道,如果焦點()和無焦點的()是真正的方法,但你的想法。您希望在按下向下鍵的同時暫時停止文本字段接受輸入,以便您可以添加自己的特殊值而不用默認響應更新其內容,然後在向下鍵爲「否」時將焦點返回到文本字段使用時間更長。
你能舉個例子嗎? – user2810895 2015-02-09 16:52:39