使用html中的箭头键浏览文本框?

时间:2017-03-15 17:35:59

标签: javascript html css

就像问题所说,我如何使用HTML中的箭头键浏览文本框?除非使用jQuery,否则。也许用JS?或者使用HTML,CSS或其他什么?谢谢!

<body>
        <form>
            <input  type="text">  <br>  
            <input  type="text">  <br> 
            <input  type="text">    
        </form>


    </body>

2 个答案:

答案 0 :(得分:0)

如果你可以使用jQuery,你可以尝试做这样的事情吗?

$('form').bind('keypress', function(event) {
  if(event.which === 38) { //up
    $(':focus').next().focus();
  }
  else if(event.which === 40) { //down
    $(':focus').prev().focus();
  }
});

不确定如何将其转换为纯粹的js

答案 1 :(得分:0)

您的HTML中没有复选框,但我们假设您稍后会这样做。

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
document.body.addEventListener('keyup', function(e){
    var leftArrow = 37;
    var rightArrow = 39;
    //get other codes from http://keycode.info/
    for(var i = 0; i < checkboxes; i++){
        //find the focused checkbox in the node list
        if(checkboxes[i] === document.activeElement){
             //if it's found, then find the next one in the node list according to the keycode
             if(e.keyCode === leftArrow){
                  (checkboxes[i-1] ? checkboxes[i-1] : checkboxes[checkboxes.length - 1]).focus()
             }

             if(e.keyCode === rightArrow){
                  (checkboxes[i+1] ? checkboxes[i+1] : checkboxes[0]).focus()
             }
             //need to get out of this loop
             break;
        }

    }

})
相关问题