English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The offset() method of jQuery gets or sets the offset coordinates of the selected element relative to the document.
When using the offset() methodGetWhen setting the offset, it will returnThe first selected elementOffset coordinates (including2an object of properties (top and left)
When using the offset() methodSetWhen setting the offset, it will setAll selected elementsoffset coordinates.
Get the offset coordinates:
$("selector").offset()
Set the offset coordinates:
$("selector").offset({top:value, left:value})
Use a function to set the offset coordinates:
$("selector").offset(function(index, currentOffset))
Get the offset coordinates of the paragraph:
$("button").click(function(){ let p = $("p"); let offset = p.offset(); p.html("left: " + offset.left + ", + offset.top); });Test and see‹/›
Set the offset coordinates of all paragraphs:
$("button").click(function(){ $("p").offset({ top: 60, left: 30 }); });Test and see‹/›
Set the offset coordinates of an element using the offset coordinates of another element:
$("button").click(function(){ $("p").offset($("div").offset()); });Test and see‹/›
Use a function to set the offset coordinates:
$("button").click(function(){ $("p").offset(function(i, val){ let newCord = new Object(); newCord.left = val.left + 100; newCord.top = val.top + 100; return newCord; }); });Test and see‹/›
Parameters | Description |
---|---|
{top:value, left:value} | Specify the top and left coordinates in pixels |
function(index, currentOffset) | Specify a function that returns an object containing the top and left coordinates
|