div,span等标签支持focus/blur事件

<div tabindex="0" hidefocus="true" onfocus='alert("得到焦点");' onblur='alert("失去焦点");' style="border:1px solid #ccc;width:200px;height:200px;outline=0;"></div>

div获得焦点

div正常情况下是无法获得焦点的,所以其blur方法和focus方法都是没有用的,解决方案如下:

<div class="fileInfo" tabindex ="0"></div>

加入tabindexdiv便可通过tab或点击的方式获得焦点,也可通过js的focus方法获得

css中去除获得焦点状态下的边框:outline:none;


DIV焦点事件

div本来是没有focusblur事件的。

如果用div来模拟一个input标签,同时需要它和input一样响应focusblur事件,就需要给他加上attribute:tabindex

只要元素的tabIndex属性设置成任何有效的整数那么该元素就能取得焦点。元素在取得焦点后就能触发onblur,onfocus,onkeydown, onkeypressonkeyup事件。

不同tabIndex值在tab order(Tabbing navigation)中的情况:

  • tabIndex值是正数的对象根据递增的值顺序和代码中的位置顺序来被选择
  • tabIndex值是0的对象根据在代码中的位置顺序被选择
  • tabIndex值是负数的对象会被忽略
obj.style.outline="none";

如果获得焦点的时候出现虚线框可以这样去除。

另外,focus并不会冒泡(w3c标准)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章