Mar 10th Wednesday
You are here: Home / Code Snippets / JavaScript / 如何在事件代理中正确使用 focus 和 blur 事件
01 月 31st ,2010

如何在事件代理中正确使用 focus 和 blur 事件

in JavaScript by Rainbow

让focus 和 blur 都支持冒泡事件的解决方案来自:

怿飞的《如何在事件代理中正确使用 focus 和 blur 事件》文章。

什么是事件代理(Event Delegation)?

如果不太了解的朋友,可详细阅读以下文章:

首先让我们一起来回顾一些常识:

  1. 通常支持事件冒泡(Event Bubbling)的事件类型为鼠标事件和键盘事件,例如:mouseover, mouseout, click, keydown, keypress
  2. 接口事件则通常不支持事件冒泡(Event Bubbling),例如:load, change, submit, focus, blur

很明显:focus 和 blur 都属于不支持冒泡的接口事件。既然都不支持冒泡,那又如何实现事件代理呢?

可以换个角度,逆向思维,尝试事件捕获(Event Capturing,除了IE,现在流行的标准浏览器均支持)。

测试后会发现,如果你捕获 focus 或 blur 事件,目标元素的祖先元素均执行事件函数。至于为什么?或许是实现的一个 BUG。

1
2
el.addEventListener('focus', focusHandler, true);
el.addEventListener('blur', blurHandler, true);

那对于 IE ,我们如何实现呢?

非常幸运,IE 下支持 focusin 和 focusout 事件,非常类似于 focus 和 blur 事件,唯一不同的是,这两种事件支持事件冒泡(Event Bubbling)。

1
2
el.onfocusin = focusHandler;
el.onfocusout = blurHandler;

很完美的解决方案:

1
2
3
4
5
6
7
if (document.addEventListener) {
    el.addEventListener('focus', focusHandler, true);
    el.addEventListener('blur', blurHandler, true);
} else {
    el.onfocusin = focusHandler;
    el.onfocusout = blurHandler;
}

 

知识扩展:

主流类库的事件代理

 

日志信息 »

该日志于2010-01-31 12:20由 Rainbow 发表在JavaScript分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

本站遵循:署名-非商业性使用-禁止演绎 3.0 共享协议

关于作者

http://CssRainBow.cn

Rainbow

我是Rainbow,珍惜着自己的梦想,因为它是我的灵魂所在!我崇尚简洁而不简单,关注WEB前端技术;重视WEB标准。

I wrote a total number of 202 articles on Rainbow.

User Comments

ADD YOURS»

还没有任何评论。

Leave a Reply

  1. Arrow

    Your Name
    一月 31st, 2010


About Me

RainBow"Cherish your visions and your dreams as they are the children of your soul; the blue prints of your ultimate achievements. "

Author : Napoleon Hill

我是Rainbow,珍惜着自己的梦想,因为它是我的灵魂所在!我崇尚简洁而不简单,关注WEB前端技术;重视WEB标准。

E-mail:CssRainBow.cn@gmail.com

更多关于我 »

About the Blog & Web Labs

WikiThis blog is targeted toward all levels of web designers and developers. All web topics are discussed, including CSS,XTMTL, Javascript (MooTools and jQuery), PHP,Java,Python and more.

注册成为会员 & 给我们投稿

Popular Topics

(X)HTML / CSS Ajax / RIA Django GoF JAVA JavaScript JavaWeb jQuery JSF JSP MooTools MySQL PHP Python

Archives

My Projects

Copyright © 2009-2010 CssRainbow.cn All rights reserved. Design by Rainbow. 冀ICP备09015604