首页 > 语言 > JavaScript > 正文

详细总结Javascript中的焦点管理

2024-05-06 14:51:38
字体:
来源:转载
供稿:网友

焦点元素

到底哪些元素可以获得焦点呢?默认情况下,只有表单元素可以获得焦点。因为只有表单元素可以交互

<input type="text" value="223">

让非表单元素获得焦点也是有办法的,先将tabIndex属性设置为-1,再调用focus()方法

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div><button id="btn">div元素获得焦点</button><script>btn.onclick = function(){ test.tabIndex = -1; test.focus(); }test.onfocus = function(){ this.style.background = 'pink';}</script>

activeElement

document.activeElement属性用于管理DOM焦点,保存着当前获得焦点的元素

[注意]该属性IE浏览器不支持

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div><button id="btn">div元素获得焦点</button><script>console.log(document.activeElement);//<body>btn.onclick = function(){ console.log(document.activeElement);//<button> test.tabIndex = -1; test.focus();  console.log(document.activeElement);//<div>}</script>

获得焦点

元素获得焦点的方式有4种,包括页面加载、用户输入(按tab键)、focus()方法和autofocus属性

【1】页面加载

默认情况下,文档刚刚加载完成时,document.activeElement中保存的是body元素的引用。文档加载期间,document.activeElement的值为null

<script>console.log(document.activeElement);//null</script><body><script>console.log(document.activeElement);//<body></script></body>

【2】用户输入(按tab键)

用户通常可以使用tab键移动焦点,使用空格键激活焦点。比如,如果焦点在一个链接上,此时按一下空格键,就会跳转到该链接

说到tab键,就不能不提到tabindex属性。tabindex属性用来指定当前HTML元素节点是否被tab键遍历,以及遍历的优先级

1、如果tabindex=-1,tab键跳过当前元素

2、如果tabindex=0,表示tab键将遍历当前元素。如果一个元素没有设置tabindex,默认值就是0

3、如果tabindex大于0,表示tab键优先遍历。值越大,就表示优先级越小

下列代码中,使用tab键时,button获得焦点的顺序是2、5、1、3

<div id="box"> <button tabindex= "3">1</button> <button tabindex= "1">2</button> <button tabindex= "0">3</button> <button tabindex= "-1">4</button> <button tabindex= "2">5</button> </div><script>box.onkeyup = function(){ document.activeElement.style.background = 'pink';}</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选