开发者

Crossbrowser onMouseenter

I'm having some issues attaching the onMou开发者_Python百科seover to a whole element and its children, so i decided to take a look at the Microsoft onMouseenter which is based on the mouse position, now i'm wondering if there is a cross browser solution, or atleast a fix for the onMouseover to be applied to the div children as well.

P.S. i'm not supposed to use jQuery or other frameworks for this.

Appreciate any ideas.


EDIT: Here's a better solution than my original. It instead tests e.relatedTarget against this.parentNode.

Seems to give accurate results:

if(  e.relatedTarget !== this.parentNode ) return;

Example: http://jsfiddle.net/FPKKX/1/

...so you'd do:

el.onmouseover = function( e ) {
    // typical event obj fix

    if(  e.relatedTarget !== this.parentNode ) return;

    // This will only log to the console for the <div>
    console.log( e.target.tagName, e.relatedTarget.tagName );
};

Original

This solution really is incomplete. It will require better per-element tracking since moving off of an inner element will fire the event on the outer. You should simply be able to do a test to replicate the behavior of mouseenter.

Example: http://jsfiddle.net/FPKKX/ (read the code comments, and open your console)

el.onmouseover = function( e ) {
    // typical event obj fix

    // if the event is the result of bubbling, return.
    if( this !== e.target ) return;

    // rest of code
};

Now the code after the if() will only fire if the target of the event is the same as the element to which the handler was applied, effectively rendering event bubbling ineffective for that event.

Note that this isn't perfect. If there are inner elements that are aligned directly against one of the inner edges of the container, the element to receive the event may be the inner one if the mouse enters at that point. Tweaking will be needed.


If you are willing to use a library such as jQuery, there is a mouseenter event which is made to be cross-browser:

http://api.jquery.com/mouseenter/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜