The easiest way to get event.offsetx with browser-compatible

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.