Many times, We all need to get the EVENT.OFFSETX value, but the Firefox event does not support the OffsetX attribute, which gives us some difficulty, although Firefox provides a Layerx property, which needs to be combined with the position property of the CSS to get the number we want. Value, which is a big limitation, he restricts the design of the page style, moreover, the value of Layerx is not strictly equivalent to the OFFSETX,OFFSETX is relative to the inner margin of the element, and the Layerx is relative to the margin, when the border is wider, the value of the two will have an error, or, The width of the border needs to be subtracted.
After searching the internet, most of the programs are calculated by offsetparent, or by using jquery's $ (e.target). Offset (). Left to calculate, or to adapt to the situation with a scroll bar, or rely on a third-party library, there is no easier way?
After study, the following calculation method is found, which is very simple:
function Getoffsetx (event) {var evt =event| | window.event; var srcobj = Evt.target | | Evt.srcelement; if (evt.offsetx) {return evt.offsetx; }else{var rect = Srcobj.getboundingclientrect (); var clientx = Evt.clientx; return clientx-rect.left; }}
Or use one line of code:
return Evt.offsetx | | (Evt.clientx-srcobj.getboundingclientrect (). left);
This method of calculation, in IE8 above, Firefox, Chrome and other browsers, are tested, in some complex page environment, the test results are correct. The only exception to this is that if the table's border property is not 0, a pixel bias will occur, and the reason is unknown.
The easiest way to get event.offsetx with browser-compatible