使div元素获得焦点 [英] Make div element receive focus
问题描述
如何使HTML <div>
元素获得焦点,以便在调用focus()
时将它们放在焦点上?
在div
上设置tabindex="0"
,前提是您希望div
接收焦点而不是子元素.>
更新了答案,添加了JS Fiddle演示,展示了实现此目的的JavaScript方法:
var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++){
divs[i].setAttribute('tabindex', '0');
}
在编写演示时,我发现tabindex="-1"
允许元素接收鼠标单击来分配焦点,但不允许键盘事件(通过 tab 按钮)分配焦点,但是(如 FabricioMatté之前的评论,tabindex="0"
允许两个都).因此,我在演示中使用了它,并更新了原始答案以反映该更改.
tabindex="0"
与tabindex="-1"
的行为记录在这里: 解决方案
Set the tabindex="0"
on the div
, on the assumption that you want the div
s to receive focus, rather than child elements.
Updated the answer to add a JS Fiddle demo, showing a JavaScript means of achieving this:
var divs = document.getElementsByTagName('div');
for (var i = 0, len = divs.length; i < len; i++){
divs[i].setAttribute('tabindex', '0');
}
While composing the demo I found that tabindex="-1"
allows the element to receive mouse-clicks to assign focus, but not keyboard events (through the tab button), however (and as implied in the comment, earlier, by Fabricio Matté, a tabindex="0"
allows for both). So I've used that in the demo, and updated the original answer to reflect that change.
Behavior of tabindex="0"
versus tabindex="-1"
documented here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex
这篇关于使div元素获得焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!