Enter key press behaves like a Tab in Javascript

后端 未结 22 1276
说谎
说谎 2020-11-27 10:52

I\'m looking to create a form where pressing the enter key causes focus to go to the \"next\" form element on the page. The solution I keep finding on the web is...

22条回答
  •  鱼传尺愫
    2020-11-27 11:33

    Vanilla js with support for Shift + Enter and ability to choose which HTML tags are focusable. Should work IE9+.

      onKeyUp(e) {
        switch (e.keyCode) {
          case 13: //Enter
            var focusableElements = document.querySelectorAll('input, button')
            var index = Array.prototype.indexOf.call(focusableElements, document.activeElement)
            if(e.shiftKey)
              focus(focusableElements, index - 1)
            else
              focus(focusableElements, index + 1)
    
            e.preventDefault()
            break;
        }
        function focus(elements, index) {
          if(elements[index])
            elements[index].focus()
        }
      }
    

提交回复
热议问题