问题
I just stumbled upon a bug in my software that happened only on Firefox. The reason was that the event didn't have offsetX and offsetY defined.
I managed to fix it thanks to this.
Anyways, my question is not a programming help request. I'm just curious why these properties are undefined in Firefox? What is the reason behind it?
I did look through: DOM3 UIEvent Spec., DOM3 MouseEvent Spec. and DOM2 MouseEvent Spec..
It appears that neither of the properties are mentioned there, so, I suppose that's an unofficial property introduced in other browsers?
回答1:
Although mentioned in the W3 specification, the offsetx
/offsety
properties themselves are implemented inconsistently across browsers.
While supported in IE, Webkit browsers and Opera, they all function slightly different to the specifications requirements, except for IE - according to the "Calculating offsetX, offsetY" section here.
The properties aren't supported in Firefox at all - it appears to be a long-time bug that is yet to be resolved.
"I suppose that's an unofficial property introduced in other browsers?"
I believe it's an official property, that just hasn't been implemented in Firefox. If it was a non-official IE property, it wouldn't have been implemented in the Webkit/Opera browsers, mentioned in the W3 spec nor would Firefox actually be trying to implement it (check out the bug link above).
回答2:
offsetX and offsetY are inconsistent in Firefox so you can do it this way
document.body.onclick = function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
rect = target.getBoundingClientRect(),
offsetX = e.clientX - rect.left,
offsetY = e.clientY - rect.top;
console.log([offsetX, offsetY]);
};
You can find more info Here and here
来源:https://stackoverflow.com/questions/17293681/why-firefox-event-offsetx-and-offsety-are-undefined