---
title: "焦点与键盘监控"
author: "yiminghe"
date: "2010-08-04T22:08:30Z"
tags: ["Firefox", "HTML5"]
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2010-08-04T22:08:30Z"
id: 729265
url: "https://yiminghe.iteye.com/blog/729265"
---

**场景：**

 

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

 

![](http://dl.iteye.com/upload/attachment/288311/3ab4c6e0-d190-325a-a730-98bf76c32682.png)

 

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

 

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

 

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

 

```
div.focus()
```

 

 

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

 

**规范与绕行：**

 

根据 [w3c html5 规范](http://www.w3.org/TR/html5/editing.html#focusable)   只有以下元素才可以获得焦点接受键盘输入，其他元素只能获得冒泡过来的键盘事件：

    * 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](http://www.w3.org/TR/html5/editing.html#attr-tabindex) （强制获得焦点顺序）或者 [contenteditable](http://www.w3.org/TR/html5/editing.html#attr-contenteditable) （使得区域可编辑）时，firefox 激活了该 div 的焦点支持，只不过这时候当div获得焦点时，div周围会有环绕虚线（可以设置[outline](http://www.w3.org/TR/CSS21/ui.html#propdef-outline-style) :none清除）。

**换个角度：**

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

[demo](http://lite-ext.googlecode.com/svn/trunk/lite-ext/playground/focus_keydown/focus_keydown.html)