tabindex 在特定元素中停止

tabindex stops in a particular element

我在我的应用程序中使用 Angular JS。我在某些可点击元素上使用 tabindex 来支持应用程序的键盘用户。

我对tabindex的理解是,假设一个元素A的tabindex = 1,元素B的tabindex = 3,元素C的tabindex = 2,那么tabbing的顺序就是A -> C -> B。然后循环继续。

我提供了以下代码片段。这部分实际上是一个模态,出现在另一个页面的顶部:

<div data-ng-if="true">
    <a tabindex="1" data-ng-click="function1()">Change Password</a>
</div>
<div>
    <a tabindex="2" data-ng-click="function2()">Manage</a>
</div>

因此,当我们开始使用 Tab 键时,预期会突出显示使用 tabindex 1 更改密码,然后使用 tabindex 2 进行管理。然后循环继续。但是,该选项卡停在管理

有人遇到过类似的问题吗?

我认为 tabindex 的工作顺序是相反的,即如果 A = 1,B = 2 和 C = 3,那么顺序是 C>B>A。

  • 如果tabindex为负值,则无法使用 tab按。
  • 如果为零,则为文档中的第一个可聚焦元素。
  • 如果为正数,元素将按升序排列 订单
  • 如果元素包含相同的 tabindex,html 中的顺序很重要。专注 按照它们在 html
  • 中的创建顺序

有关详细信息,请阅读 tabindex

最重要的是,浏览器 url 框的 tabindex 为 0

我最近接到一个任务,通过 tab 和 shift-tab 循环关注元素。因此,我创建了一个自定义指令。可以找到工作演示 here.

已更新HTML:

  <div data-ng-if="true">
    <a tabindex="1" id="idChangePassword" focus-next="idManage" focus-on-tab="0" data-ng-click="function1()">Change Password</a>
  </div>
  <div>
    <a tabindex="2" id="idManage" focus-next="idChangePassword" focus-on-tab="1" data-ng-click="function2()">Manage</a>
  </div>

指令代码:

angular.module("myApp.directives", []).directive("focusNext", function() {
  return {
    restrict: "A",
    link: function($scope, elem, attrs) {
      elem.bind("keydown", function(e) {
        var code = e.keyCode || e.which;
        console.log(e);
        if (code === 9 && e.shiftKey === true && attrs.focusOnTab === "0") {
          e.preventDefault();
          document.getElementById(attrs.focusNext).focus();
        } else if (
          code === 9 &&
          e.shiftKey === false &&
          attrs.focusOnTab === "1"
        ) {
          console.log("tab");
          e.preventDefault();
          document.getElementById(attrs.focusNext).focus();
        } else {
          return true;
        }
      });
    }
  };
});

请注意,TAB 键聚焦下一个元素,SHIFT-TAB 键聚焦上一个元素。

如何使用指令?

如果要将元素 X 中的元素 Y 聚焦到 SHIFT-TAB 按下,然后在 X 元素中添加 focus-next="idofY" focus-on-tab="0"

如果你想在TAB键上从元素Y聚焦元素X,然后在Y元素中添加focus-next="idOfX" focus-on-tab="1"

确保需要聚焦的元素默认支持tabindex,如果不支持则添加tab-index="0" 到该元素。