msgbartop
PHP源码分析,Zend引擎分析,Web相关技术研究,Web技术分享–左手代码 右手诗
msgbarbottom

18 Jul 08 Dom事件的srcTarget,strElement探幽

    我们知道在Javascript中,可以使用事件处理函数来监听事件,在事件处理函数中,我们可以通过当前的事件对象(IE: window.event ; firefox parameter event)来获取到事件发生的对象。
    比如,在IE中
     

 function eventHandler = function(e){
     var ev = e || window.event ; //window.event for IE, para e for ff
     var el = evt.srcTarget || evt.srcElement; // compatible with IE
     //then el is the target which cause the event
}

      那么,JS内部是如何通过event获取到srcTarget呢? 一直以来,我以为srcTarget会保留一个到事件发生对象的引用,但今天遇到的一个问题,让我改变了看法:    一个Div,上面有个blur时间,当失去焦点的时候就会display=none, Div中包含几个<a>标签,在这些标签上监听了click事件。

    问题出现了,因为当你click一个A的时候,blur时间被触发了,那么这个DIV就display none了,紧接着click事件被触发,问题就是,这个时候,在click函数中,取不到正确的srcTarget了。

     经过一番折腾,最后使用了个比较hacker的方法来解决,就是在blur事件函数中,这样:

     setTimeout(function(){div.style.display=’none’;}, 100);

     回头来想,我猜测,Javascript中的srcElement的获取机制如下:

     事件发生时,event对象记录事件的鼠标坐标,但并不记录发生事件对象的引用,只有当你去获取srcTarget的时候,JS解释器,会根据event的鼠标坐标去获取该坐标的元素。

     当然,这只是个简单猜想,还没有去仔细验证,唉,不开源的东西搞起来就是麻烦,还要猜啊猜的。

     如果谁知道具体机理,欢迎来信指教。   

Related Posts:

  • No Related Post

Tags: , ,

Reader's Comments

  1. |

    你这个例子是先触发 blur,所以 a 隐藏了,因此 a 是压根不会触发任何东东 (都隐藏了,你还 click 啥)。我在 Firefox 下面测试过,确实如此,我觉得跟事件机制没有任何关系。

  2. |

    问题是a标签上的click事件处理器被触发了。

  3. |

    恩,我根据你的例子做过测试,在 Firefox 下面 a 是不会触发 onclick 的,但是你的那个 div 是如何绑定 blur 事件的?我这样写无办法绑定到事件哦。

    这是自写的 bind 方法:
    function bind(o, type, handle) {
    var el = document.getElementById(o);
    if (el) {
    if (el.addEventListener) {
    el.addEventListener(type, handle, false);
    } else {
    el.attachEvent(‘on’ + type, handle);
    }
    }
    }

    bind(‘div’, ‘blur’, function(e) {…});

    这样,div 的 blur 无办法触发啊,我看过 dhtml 好像 div 没有 blur 事件的哦,愿赐教…

  4. |

    这是事件的冒泡问题
    IE是由外到内,FF刚好相反是由内到外的触发顺序,是否冒泡是可以在用attach event时设定。
    详细见
    http://www.quirksmode.org/js/events_order.html

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word