返回值:Objectoffset()
Get the current coordinates of the first element in the set of matched elements, relative to the document.
-
1.2 新增offset()
The .offset()
method allows us to retrieve the current position of an element relative to the document. Contrast this with .position()
, which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop),
.offset()
is the more useful.
.offset()
returns an object containing the properties top
and left
.
Note: jQuery does not support getting the offset coordinates of hidden elements.
示例:
Access the offset of the second paragraph:
<!DOCTYPE html>
<html>
<head>
<style>
p { margin-left:10px; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
</script>
</body>
</html>
演示:
示例:
Click to see the offset.
<!DOCTYPE html>
<html>
<head>
<style>
p { margin-left:10px; color:blue; width:200px;
cursor:pointer; }
span { color:red; cursor:pointer; }
div.abs { width:50px; height:50px; position:absolute;
left:220px; top:35px; background-color:green;
cursor:pointer; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="result">Click an element.</div>
<p>
This is the best way to <span>find</span> an offset.
</p>
<div class="abs">
</div>
<script>
$("*", document.body).click(function (e) {
var offset = $(this).offset();
e.stopPropagation();
$("#result").text(this.tagName + " coords ( " + offset.left + ", " +
offset.top + " )");
});
</script>
</body>
</html>