是否可以使HTML元素不可聚焦?
我知道可以定义可以获得焦点的元素列表,并且用户可以通过Tab按键来浏览这些元素.我也看到由浏览器来控制它.
但也许有一种方法可以使某些元素不可聚焦,比如说我希望用户<a>在按下时跳过某个标签Tab.
Fed*_*kov 80
<a href="http://foo.bar" tabIndex="-1">unfocusable</a>
Run Code Online (Sandbox Code Playgroud)
负值表示该元素应该是可聚焦的,但不应通过顺序键盘导航访问.
https://developer.mozilla.org/nl/docs/Web/HTML/Global_attributes/tabindex
Ran*_*ndy 19
要完全阻止焦点,不仅仅是在使用tab按钮时,请disabled在HTML元素中设置为属性.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<input class="form-control" type="text"> Click this, you can see it's focusable.
<input class="form-control" type="text" readonly> Click this, you can see it's focusable.
<input class="form-control" type="text" readonly tabindex="-1"> Click this, you can see it's focusable. Not tab'able.
<input class="form-control" type="text" disabled> Click this, you can see it's <strong>not</strong> focusable.Run Code Online (Sandbox Code Playgroud)
TabIndex 是您要查找的内容:http : //www.w3schools.com/jsref/prop_html_tabindex.asp。
当您将 tabIndex 值设置为 -1 时,您将在通过 Tab 键浏览表单时跳过它。
为了防止某个元素获得焦点(“不可聚焦”),您需要使用Javascript来监视focus和防止默认交互。
为了防止元素被制表到,使用tabindex=-1属性。
添加tabindex=-1将使任何元素都具有焦点,甚至是div元素。这意味着,当用户单击它时,它可能会获得焦点轮廓,具体取决于浏览器。
理想情况下,您需要这样做:
function preventFocus(event) {
event.preventDefault();
if (event.relatedTarget) {
// Revert focus back to previous blurring element
event.relatedTarget.focus();
} else {
// No previous focus target, blur instead
event.currentTarget.blur();
}
}
/* ... */
element.setAttribute('tabindex', '-1');
element.addEventListener('focus', preventFocus);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55605 次 |
| 最近记录: |