ITeye博客

焦点与键盘监控

yiminghe · 2010-08-04 22:08 · javascript · Web前端 · HTML5 · Firefox · Markdown

场景:

 

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

 

 

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

 

div.on("keydown",function(){
//上
//下
});

 

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

 

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

评论(4)

  1. #4 楼 · yiminghe · 2010-08-16 16:12

    cloudgamer writes:

    tabIndex设-1就可以了

    这个方法我说了啊:

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

  2. #3 楼 · cloudgamer · 2010-08-16 14:16

    tabIndex设-1就可以了

  3. #2 楼 · yiminghe · 2010-08-04 23:38

    luolonghao writes:

    谢谢分享,看你们的loadmap下半年很多功能要发布,很期待的。 PS,发现Kissy Editor也简称KE :)

    哈哈,我也觉得很奇妙 CKEditor KindEditor KissyEditor

    貌似我们是最山寨的一个 :x

  4. #1 楼 · luolonghao · 2010-08-04 22:32

    谢谢分享,看你们的loadmap下半年很多功能要发布,很期待的。 PS,发现Kissy Editor也简称KE :)

评论功能维护中,当前仅展示历史评论。