【问题标题】:Is there a way to set tabIndex of an element to last in the tabIndex loop without assigning tabIndex to all elements in DOM?有没有办法在不将 tabIndex 分配给 DOM 中的所有元素的情况下将元素的 tabIndex 设置为 tabIndex 循环中的最后一个?
【发布时间】:2020-04-19 21:24:32
【问题描述】:

我正在尝试以多个输入字段和多个按钮的形式自定义 tabIndex 顺序。由于表单中的元素是动态的,因此将 tabIndex 分配给每个元素有点复杂。 根据默认流程,表单中的一个按钮位于 tabIndex 循环的中间,但我希望它位于 tabIndex 循环的末尾。有没有办法设置按钮/元素的 tabIndex 以使其接近循环结束?如果在不使用 jQuery 为表单/DOM 中的所有其他元素设置 tabIndex 的情况下可以做到这一点,那就太好了

【问题讨论】:

  • 你试过给按钮一个很高的tabindex值吗?仅供参考,最大值为 32767。
  • 无论是直接在 tabIndex 属性上还是通过 JS 分配此值,您都不会以某种方式逃避输入顺序的保留。
  • @terrymorse 是的,通过给出高索引进行了尝试。没有成功
  • @lime_pal 请参阅下面的建议和示例。

标签: javascript html css


【解决方案1】:

不赞成使用tabindex 调整选项卡元素的顺序。正如MDN web doc on tabindex 所说:

避免使用大于 0 的 tabindex 值。这样做会使依赖辅助技术的人难以导航和操作页面内容。相反,用逻辑顺序的元素编写文档

首选方法是简单地重新排序元素,而不是使用 tabindex 重新排序。

因此,如果有一个按钮排序不正确,请将其移动到正确的位置。

一个例子:

// move button with matching ID to last position
function moveBtn(btnID) {
  let wrongSpot = document.getElementById(btnID);
  wrongSpot.parentElement.appendChild(wrongSpot);
}
/* optional styling */
#div-form {
  border: 1px solid #bbb;
  padding: 0.5rem;
  width: 20rem;
}

input, button {
  display: block;
  margin: 0.4rem 0;
}
<p>Moving Button to Last Position:</p>

<div id="div-form">
  <input placeholder="input1" />
  <button id="wrong-spot">Button</button>
  <input placeholder="input2" />
</div>

<button onclick="moveBtn('wrong-spot');">Move Button</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2012-03-06
    • 1970-01-01
    • 2018-08-16
    • 2023-02-15
    相关资源
    最近更新 更多