jQuery offset()Method

jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Example

Return the offset coordinates of a <p> element:

$("button").click(function(){ var x=$("p").offset(); alert("Top: " + x.top + " Left: " + x.left); });

Try it Yourself »

Definition and Usage

The offset() method sets or returns the offset coordinates of the selected element relative to the document.

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

When used to set the offset:
This method sets the offset coordinates of all matched elements.


Syntax

Return the offset coordinates:

$(selector).offset()

Set the offset coordinates:

$(selector).offset({top:value,left:value})

Set the offset coordinates using a function:

$(selector).offset(function(index,currentoffset))

Parameters Description
{top:value,left:value} Required when setting the offset. Specifies the top and left coordinates in pixels.

Possible values:
  • Name/value pairs, such as {top:100,left:100}
  • An object with top and left (Example)
function(index,currentoffset) Optional. Specifies a function that returns an object containing the top and left coordinates.
  • index- Returns the index position of the element in the set.
  • currentoffset- Returns the current coordinates of the selected element.


实例

More Examples

Set offset coordinates
How to set the offset coordinates of an element.

Set offset coordinates using a function
How to set the offset coordinates of an element using a function.

Set offset coordinates for an element using an object
How to set the offset coordinates of an element using a new object.

Set offset coordinates for an element using another element's offset coordinates
How to set the offset coordinates of an element using the offset coordinates of another element.


jQuery HTML/CSS 方法jQuery HTML/CSS Methods

Other Extensions