2015-02-09 62 views
0

我正在制作一个应支持下标的自定义输入字段。当用户按下向下箭头+一个数字时,该数字应该在下标中。我将一个onKeyDown和onKeyUp事件监听器添加到内容可编辑段落中。不幸的是,当用户按下数字时,onKeyUp被调用,导致数字加两次(一次在下标和一次正常)。我怎么解决这个问题?按下第二个按钮时调用onKeyUp

function keyDown(event) { 
    var code = event.keyCode; 
    if (code === 40) { 
     option = 0; 
    } 
} 

function keyUp(event) { 
    var code = event.keyCode; 
    if (code === 40 || code === 38) { 
     option = -1; 
    } 
    console.log("release"); 
} 

onKeyPressed不是一个选项,因为它无法识别所有浏览器中的箭头键。有没有本地解决方案(没有jQuery)?

回答

0

我最常做的是将keyCodes推入一个阵列keyDown.splice()keyUp

现在您只需检查(可能是针对预定义的地图)您希望的按键状态是否在阵列中可用。

+0

你能举个例子吗? – user2810895 2015-02-09 16:52:39

0

只要您的文本字段具有焦点,除了您的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. 
    } 
} 

再次,我只想说,这个代码没有经过测试,我不知道,如果焦点()和无焦点的()是真正的方法,但你的想法。您希望在按下向下键的同时暂时停止文本字段接受输入,以便您可以添加自己的特殊值而不用默认响应更新其内容,然后在向下键为“否”时将焦点返回到文本字段使用时间更长。

相关问题