在容器中的<em>元素之间导航

时间:2018-06-13 11:21:44

标签: javascript jquery html

给定页面中的容器div,如何将焦点放在某个元素上?

我尝试了以下内容:

<div id="modalTextDocument" style="height:15px;overflow:scroll;">
<em>Hello</em>
... various text...
<em>other highlighted element<em> you can see this only scrolling...
etc...
</div>

这个jQuery代码不起作用:

$('div#modalTextDocument').find('em')[1].focus();

1 个答案:

答案 0 :(得分:0)

快速解决方案是为tabindex为您要定位的每个元素添加focus,默认情况下无法调焦。

通过指定tabindex,您基本上可以告诉浏览器元素应该获得焦点的顺序,而且您可以为任何元素设置tabindex,而不仅仅是那些能够默认接收焦点的元素。

$('div#modalTextDocument').find('em')[1].focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modalTextDocument">
  <em tabindex="1">Hello</em>
  ... various text...
  <em tabindex="2">other highlighted element</em> you can see this only scrolling...
  etc...
</div>

现在,您可以通过点击other highlighted element或点击它们来关注Hellotab(或者您也可以像上面的代码一样以编程方式设置焦点)。