zoukankan      html  css  js  c++  java
  • 焦点与键盘监控

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

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

    Js代码:

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

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

    Js代码:

    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,一样可以达到效果。

    示例:

  • 相关阅读:
    深度学习(dropout)
    centos 常见软件安装
    最近读的书 与论文
    如何理解反向传播 Backpropagation 梯度下降算法要点
    ubuntu 15 安装cuda,开启GPU加速
    快速排序算法
    Linux网络中接收 "二进制" 流的那些事 --- 就recv的返回值和strlen库函数进行对话
    linux源码升级编译内核
    C/C++中慎用宏(#define)
    Qt之hello world
  • 原文地址:https://www.cnblogs.com/fengyuqing/p/htmlElement_keyboard_event.html
Copyright © 2011-2022 走看看