How to get the coordinates of the mouse in JS

Source: Internet
Author: User

CopyCode The Code is as follows: var X, Y;

// When the requirement is that the obtained coordinate value is relative to the body, use:

Function positionbody (event ){

Event = event | window. event;

// Obtain the horizontal value relative to the body position;

X = event. clientx

// Obtain the vertical value relative to the positioning of the body;

Y = event. clienty

}

// When the requirement is that the obtained coordinate value is relative to an object, use:

Function positionobj (event, ID ){

// Obtain the abscissa value of the object relative to the page. The ID is the ID of the object.

VaR thisx = Document. getelementbyid (ID). offsetleft;

// Obtain the abscissa value of the object relative to the page;

VaR thisy = Document. getelementbyid (ID). offsettop;

// Obtain the Page scrolling distance;

// Note: document.doc umentelement. scrolltop supports non-Google kernels, and document. Body. scrolltop supports Google kernels.

VaR thisscrolltop = document.doc umentelement. scrolltop + document. Body. scrolltop;

Event = event | window. event;

// Obtain the abscissa value relative to the object positioning = the abscissa value of the current page relative to the mouse-the abscissa value of the object;

X = event. clientx-thisx;

// Obtain the vertical value relative to the object positioning = the vertical coordinate value of the current mouse relative to the page-the object vertical coordinate value + the scroll height of the scroll bar;

Y = event. clienty-thisy + thisscrolltop;

}

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.