焦点管理

焦点元素

通常情况下,只有可交互的元素能够获取焦点,比如表单元素、超链接。如果要让不可交互元素获得焦点,需要做特殊处理:先将tabIndex属性设置为-1,再调用focus()方法

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

activeElement属性

document.activeElement属性保存着当前获得焦点的元素。默认情况下,文档加载期间,document.activeElement的值为null;文档刚刚加载完成时,document.activeElement中保存的是body元素的引用。

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

获得焦点

元素获得焦点的方式有3种:按tab键、focus()方法和autofocus属性

按tab键

用户可以通过tab键移动焦点,使用空格激活焦点。tab键常常配合元素的tabindex属性一起使用,tabindex属性用来指定当前HTML元素节点是否被tab键遍历,以及遍历的优先级

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

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

3、如果tabindex大于0,表示tab键优先遍历

<div id="box">
    <button tabindex= "-1">4</button>
    <button tabindex= "0">3</button>
    <button tabindex= "1">2</button>
    <button tabindex= "2">5</button>    
    <button tabindex= "3">1</button>
</div>
<script>
box.onkeyup = function(){
  document.activeElement.style.background = 'pink';
}
</script>

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

focus()

focus()方法用于将浏览器的焦点设置到表单字段,即激活表单字段,使其可以响应键盘事件

<input id="test">
<button id="btn">焦点</button>
<script>
  btn.onclick = function() {
    test.focus()
  }
</script>

autofocus

HTML5表单字段新增了autofocus属性,设置这个属性后,能自动把焦点移动到相应字段

<input autofocus>

hasFocus()

document.hasFocus()方法返回一个布尔值,表示当前文档之中是否有元素被激活或获得焦点

console.log(document.hasFocus());// true

失去焦点

blur()方法的可以从元素中移走焦点

<input id="test" autofocus>
<button id="btn">失去焦点</button>
<script>
  btn.onclick = function() {
    test.blur()
  }
</script>

焦点事件

焦点事件会在页面获得或失去焦点时触发

blur

blur事件在元素失去焦点时触发。这个事件不会冒泡

focus

focus事件在元素获得焦点时触发。这个事件不会冒泡

focusin

focusin事件在元素获得焦点时触发。这个事件与focus事件等价,但它冒泡

focusout

focusout事件在元素失去焦点时触发。这个事件与blur事件等价,但它冒泡

注意: focusin和focusout需要使用DOM2级事件处理程序

<input type="text" id="t1">
<input type="text" id="t2">
<script>
  t1.onfocus = function() {
    this.style.background = 'green';
  }
  t1.onblur = function() {
    this.style.background = 'red';
  }
  t2.addEventListener('focusin', function(){
    this.style.background = 'green'
  }, false)
  t2.addEventListener('focusout', function(){
    this.style.background = 'red'
  }, false)
</script>
posted @ 2021-09-28 18:47  wmui  阅读(81)  评论(0编辑  收藏  举报