使div元素获得焦点 [英] Make div element receive focus

查看:1086
本文介绍了使div元素获得焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使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');
}

JS小提琴演示.

在编写演示时,我发现tabindex="-1"允许元素接收鼠标单击来分配焦点,但不允许键盘事件(通过 tab 按钮)分配焦点,但是(如 FabricioMatté之前的评论,tabindex="0"允许两个都).因此,我在演示中使用了它,并更新了原始答案以反映该更改.

tabindex="0"tabindex="-1"的行为记录在这里: 解决方案

Set the tabindex="0" on the div, on the assumption that you want the divs 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');
}

JS Fiddle demo.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆