Html 使 div 元素获得焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16261504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make div element receive focus
提问by Chito Adinugraha
How can I make an HTML <div>
element receive focus, so elements will be put into focus when focus()
is called on them?
如何使 HTML<div>
元素获得焦点,以便在focus()
调用元素时将其置于焦点?
回答by David says reinstate Monica
Set the tabindex="0"
on the div
, on the assumption that you want the div
s to receive focus, rather than child elements.
设置tabindex="0"
on div
,假设您希望div
s 获得焦点,而不是子元素。
Updated the answer to add a JS Fiddle demo, showing a JavaScript means of achieving this:
更新了答案以添加 JS Fiddle 演示,显示了实现此目的的 JavaScript 方法:
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 tabbutton), 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.
在编写演示时,我发现tabindex="-1"
允许元素接收鼠标点击以分配焦点,但不允许接收键盘事件(通过tab按钮),但是(正如之前的Fabricio Matté在评论中暗示的那样,atabindex="0"
允许两者)。所以我在演示中使用了它,并更新了原始答案以反映这种变化。
Behavior of tabindex="0"
versus tabindex="-1"
documented here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex
此处记录的tabindex="0"
vs行为tabindex="-1"
:https: //developer.mozilla.org/en-US/docs/Web/Accessibility/Keyboard-navigable_JavaScript_widgets#Using_tabindex