焦点与键盘监控

场景:

常常会碰到这样的场景,需要加强对键盘的支持,比如搜索提示支持键盘导航,以及数据列表支持pagedown等翻页,

而这些数据的容器常常都是div,为了效率考虑,我们一般不在document上监控键盘,而直接在容器div上监控:

Java代码 复制代码 收藏代码
  1. div.on("keydown",function(){   
  2. //上   
  3. //下   
  4. });  
div.on("keydown",function(){
//上
//下
});

并且在衔接过程中,直觉得使用

Js代码 复制代码 收藏代码
  1. div.focus()  
div.focus()
 

来使得容器获得焦点,试图使得div处于焦点内可以接受键盘输入,但是很不幸的是 firefox 并不可行。

规范与绕行:

根据 w3c html5 规范   只有以下元素才可以获得焦点接受键盘输入,其他元素只能获得冒泡过来的键盘事件:

 

    * a elements that have an href attribute
    * link elements that have an href attribute
    * button elements that are not disabled
    * input elements whose type attribute are not in the Hidden state and that are not disabled
    * select elements that are not disabled
    * textarea elements that are not disabled
    * command elements that do not have a disabled attribute
    * Elements with a draggable attribute set, if that would enable the user agent to allow the user to begin a drag operations for those elements without the use of a pointing device

 

 

那么普通的 div focus 方法就被 firefox 忽略了,但是当 div 设置了属性 tabindex (强制获得焦点顺序)或者 contenteditable (使得区域可编辑)时,firefox 激活了该 div 的焦点支持,只不过这时候当div获得焦点时,div周围会有环绕虚线(可以设置outline :none清除)。

 

换个角度:

 

其实我们不需一定要div自身获得焦点支持键盘事件,只要其内的子元素获得焦点接受事件,div这边只需捕获冒泡过来的事件即可,那么我们可以在容器内生成一个高宽为0的 带有 href 属性的a节点(同样注意 outline 清除),当需要div监控键盘时,只要调用 div 内的 a.focus() ,那么键盘输入就会被a接受,并冒泡到父容器 div,一样可以达到效果。

 

demo

原文地址:https://www.cnblogs.com/lteal/p/3148210.html