Home  >  Article  >  Web Front-end  >  How to get the coordinates of an element with jQuery?

How to get the coordinates of an element with jQuery?

青灯夜游
青灯夜游Original
2020-11-17 11:06:293782browse

How to get element coordinates with jQuery: 1. Use offset() to get the absolute X and Y coordinates of an element on the page, using the syntax "$(element).offset().top" and "$(element) ).offset().left"; 2. Use position() to obtain the position coordinates of the element relative to the parent element.

How to get the coordinates of an element with jQuery?

[Related recommendations: jQuery Video Tutorial]

jQuery Gets the Coordinates of Elements

1. To obtain the absolute X and Y coordinates of an element on the page, you can use offset():

var X = $(‘#div1’).offset().top;
var Y = $(‘#div1’).offset().left;

offset() Method returns or sets the offset (position) of the matching element relative to the document.

When used to return offset: This method returns the offset coordinate of the first matching element. It returns an object with two properties (top and left position in pixels).

2. Get the relative (parent element) position:

var X = $(‘#div1’).position().top;
var Y = $(‘#div1’).position().left;

position() method returns the position of the first matching element (relative to its parent element).

This method returns an object with two properties (top and left positions in pixels).

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of How to get the coordinates of an element with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn