Cross Browser Event object normalization?

2020-07-11 07:10发布

问题:

I'm looking for a good resource on event normalization on the event object. I'm trying to do it myself but I keep feeling like I'm going to miss something.

Here's what I have so far, tell me if I missed anything.

var eFix = function(e) {
    e = e || window.event;
    e.target = e.target || e.srcElement;
    e.offsetX = e.offsetX || e.layerX;
    e.offsetY = e.offsetY || e.layerY;
    e.relatedTarget = e.relatedTarget ||
        e.type == 'mouseover' ? e.fromElement : e.toElement;
    e.target = e.target || e.srcElement;
    if (target.nodeType === 3) target = target.parentNode; //Safari bug
    return e;
};

Has anyone seen a complete normalization function? Did I miss anything? (Needless to say we're going for W3C model not IE)

回答1:

There is another problem with your code:

e.layerX only works on positioned elements, so at the very least you need to add a "position:relative" to your element to function. Secondly e.offsetX only works correctly in IE8 and later, so you should probably refrain from using it either way (although I am using them right now, but this only needs to work in specific browsers).