【问题标题】:Tab index to jump between only 2 text boxes选项卡索引仅在 2 个文本框之间跳转
【发布时间】:2018-07-12 19:45:59
【问题描述】:

我的页面上有各种元素,但是我只希望通过按 Tab 键访问 2 个文本框,并不断按 Tab 键在它们之间来回切换。实现这一目标的最佳方法是什么?

下面的一些相关代码:

<input id="messageBox" placeholder="Type your message here... " tabindex="1" autocomplete="off" /> 
<input id="guessBox" placeholder="Type your guess here..." tabindex="2" autocomplete="off" />

<button id="btnRankUp">Rank Up</button>
<button id="btnHint">Hint</button>
<div id="audioControl">Volume:</div>
<input id="vol-control" type="range" min="0" max="100" step="1" />
<button id="btnMute">Mute</button>

【问题讨论】:

  • 检查这个问题一次:stackoverflow.com/questions/14314659/…
  • 或者按钮是用来点击的,而文本框是用来输入的,所以为了防止用户把手从键盘上移开来在两个文本框之间切换,我可以得到这个标签索引去工作。当用户需要点击一个按钮时,他们可以通过将手从键盘上移到鼠标上来完成。请不要对我的问题提出毫无意义的问题,谢谢:)

标签: html tabindex


【解决方案1】:

监听TAB按下第二个按钮并将第一个元素聚焦在此事件上。

var first = document.getElementById('guessBox'),
    second = document.getElementById('messageBox')

first.onkeydown = function(e) {
  if (e.keyCode === 9) { // the keycode for TAB is 9
    second.focus()
    e.preventDefault()
  }
}
<input id="messageBox" placeholder="Type your message here... " tabindex=0 autocomplete="off" />
<input id="guessBox" placeholder="Type your guess here..." autocomplete="off" />

<button id="btnRankUp">Rank Up</button>
<button id="btnHint">Hint</button>
<div id="audioControl">Volume:</div>
<input id="vol-control" type="range" min="0" max="100" step="1" />
<button id="btnMute">Mute</button>

在这里玩:https://jsfiddle.net/m6btzgpy/

(我不知道为什么tabindex=1 没有在标签顺序中将元素放在首位,但它适用于0

【讨论】:

    【解决方案2】:

    对于其余元素,您需要为其他(无法切换)元素设置tabindex="-1"

    仅 HTML 解决方案:

    <input id="messageBox" placeholder="Type your message here... " autocomplete="off" /> 
    <input id="guessBox" placeholder="Type your guess here..." autocomplete="off" />
    
    <button id="btnRankUp" tabindex="-1">Rank Up</button>
    <button id="btnHint" tabindex="-1">Hint</button>
    <div id="audioControl" tabindex="-1">Volume:</div>
    <input id="vol-control" type="range" min="0" max="100" step="1" tabindex="-1" />
    <button id="btnMute" tabindex="-1">Mute</button>
    

    但是你也可以用 JS 来处理。您只需为所有不是input 父母的孩子设置相同的tabindex="-1"

    来源:How to ignore HTML element from tabindex?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 2016-08-16
      相关资源
      最近更新 更多