防止某些元素获得焦点

Geo*_*ith 15 html javascript jquery accessibility

所以我有以下功能.它的作用是监听所有元素的焦点事件.如果该元素处于$mobileMenu$menuItems允许它,否则它将删除焦点:

var $body = $("body");
var $mobileMenu = $("#mobile-menu");
var $menuItems = $("#main-menu a");

$body.on("focus.spf", "*", function(e){
  e.stopPropagation();
  $this = $(this);

  // Prevent items from recieving focus and switching view
  if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
    $this.blur();
  } else {
    console.log(this);
  }
})
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,如果现在不可聚焦的正常可聚焦元素先于我列出的任何白色元素,这会阻止用户专注于任何事情,因为它只是试图一遍又一遍地重新聚焦在同一个元素上.

有谁知道我怎么能告诉它而不是跳到下一个可聚焦的元素?

dav*_*rad 5

这有效(更新):

$body.on("focus.spt", "*", function(e){
  $this = $(this);
  if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
    $this.blur();
    var next=$this.nextAll().find('a,input');
    if (next.length>0) next[0].focus();
  } else {
    console.log('ok',this);
    e.stopPropagation();
  }
})
Run Code Online (Sandbox Code Playgroud)

(更新) fiddle -> http://jsfiddle.net/CADjc/ 您可以在控制台中看到哪些元素接收焦点(main-menu amobile-menu)

测试:

<input type="text" tabindex="1" value="test">
<span><input type="text" tabindex="2" value="test"></span>
<div><input type="text" id="mobile-menu" tabindex="3" value="mobile-menu"></div>
<div><span>
    <div id="main-menu">
        <a tabindex="4">main-menu</a>
        <a tabindex="5">main-menu</a>
    </div>
</span></div>
<span>
<input type="text" tabindex="6" value="test">
</span>
Run Code Online (Sandbox Code Playgroud)


Har*_*nen 5

如果你禁用某些东西,它就不会获得焦点。例如:

<input type="text" disabled="disabled" />
Run Code Online (Sandbox Code Playgroud)

以编程方式添加它,你可以这样做:

var el = document.getElementById('disableme');
el.setAttribute('disabled', 'disabled');
Run Code Online (Sandbox Code Playgroud)

  • 提交表单时,禁用的输入元素不会发送到服务器。与当前情况没有太大关系,但最好记住。 (2认同)
  • 我的建议是将“某物”一词替换为“表单元素”,因为“禁用”仅适用于表单元素,而不适用于其他元素。 (2认同)

npn*_*pnp 5

如果在元素上将tabindex设置为“ -1”,它将忽略该选项卡。不确定这是否适用于所有浏览器,但适用于Google Chrome。

<input type="text" tabindex="-1"/>
Run Code Online (Sandbox Code Playgroud)

  • 垂直同步对此答案进行了不必要的更新。它使给出的原始答案过于复杂。 (2认同)