首页 > 解决方案 > Shift focus onkeydown - JavaScript Only - No jQuery

问题描述

I would like to be able to navigate through some of the focusable elements on my webpage with the arrow keys, using JavaScript only.

I found a great solution here. Only thing is, it uses jQuery, which I don't want to use. I was told by the author of that answer that it is possible to achieve the same effect with JavaScript only. I just don't know how, or even what to look for. I'm still a beginner, so I am sorry if it is an obvious question.

This is the jQuery version of what I want to achieve:

<input class='move' /><input class='move' /><input class='move' />

$(document).keydown(
    function(e)
    {    
        if (e.keyCode == 39) {      
            $(".move:focus").next().focus();
        }
        if (e.keyCode == 37) {      
            $(".move:focus").prev().focus();
        }
    }
);

标签: javascriptjqueryhtmlcssfocus

解决方案


You can use the following functions:

  • querySelectorAll() or getElementsByClassName for selecting elements.
  • addEventListener() for binding the event listener.
  • previousElementSibling and nextElementSibling for getting the previous() and next() elements.

var inputs = document.getElementsByClassName("move");
for (var i = 0; i < inputs.length; i++)
  inputs[i].addEventListener("keyup", function (event) {
    if (event.keyCode == 37) {
      if (this.previousElementSibling) {
        this.previousElementSibling.focus();
      }
    }
    else if (event.keyCode == 39) {
      if (this.nextElementSibling) {
        this.nextElementSibling.focus();
      }
    }
  }, false);
<input class='move' />
<input class='move' />
<input class='move' />

For more replacement stuff, check out: You Might Not Need jQuery.


推荐阅读