DOM 元素如何获得焦点

首先让我们看看哪些元素可以直接获得焦点(element..focus()):

// Form : 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
  • Each shape that is generated for an area element

而除上面以外的元素(比如:div,p)一般都无法直接获得焦点,那如何处理呢?

  1. 给元素添加 contenteditable 属性。

    // From : http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#attr-contenteditable

    User agents must make editing hosts focusable (which typically means they enter the tab order).

  2. 给元素添加 tabindex 属性。

    // From : http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#attr-tabindex

    The tabindex content attribute specifies whether the element is focusable, whether it can be reached using sequential focus navigation, and the relative order of the element for the purposes of sequential focus navigation.

    非常推荐使用 tabindex = -1 ,基本无副作用!!

    // From : http://www.w3.org/TR/2009/WD-html5-20090423/editing.html#attr-tabindex

    If the value is a negative integer: The user agent must allow the element to be focused, but should not allow the element to be reached using sequential focus navigation.

综述,使无法直接获得焦点的元素获得焦点的最佳实践就是:给元素添加 tabindex = -1 属性。

当然你还可以通过子元素(focusable)的 focus 事件的捕获或冒泡来模拟,但需要处理事件的浏览器兼容(《如何在事件代理中正确使用 focus 和 blur 事件》)。

 

http://www.planabc.net/2010/11/18/how_to_get_focus/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值