如何使用jQuery获得一个元素相对于文档或父级的位置
为了获得一个元素相对于文档的位置,jQuery offset()方法被使用。offset()方法是jQuery内置的一个方法,用于设置或返回所选元素的偏移坐标。我们还可以使用jQuery的position()方法。position()方法是一个jQuery的内置方法,它是用来找到第一个匹配的元素相对于它的父元素在DOM树中的位置。
语法:
$(selector).offset()
下面的例子说明了上述方法。
示例 1:
<!DOCTYPE html>
<html>
<head>
<title>
How to get the Location of
an element relative to the
document using jQuery?
</title>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
</style>
<script src=
"https://code.jquery.com/jquery-1.12.4.min.js">
</script>
</head>
<body>
<h1>GeeksforGeeks</h1>
<b>
How to get the Location of an
element relative<br> to the
document using jQuery/JavaScript?
</b>
<br><br>
<div id="Logo">
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200121112744/logo11.png">
</div>
<br><br>
<button type="button">Click</button>
<h4></h4>
<script>
(document).ready(function() {
("button").click(function() {
var offset = ("#Logo").offset();
("h4").text("Location of the box is: (left: " +
offset.left + ", top: " + offset.top + ")");
});
});
</script>
</body>
</html>
输出:
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>
How to get the Location of
an element relative to the
document using jQuery?
</title>
<style>
h1 {
color: green;
}
body {
text-align: center;
}
</style>
<script src=
"https://code.jquery.com/jquery-1.12.4.min.js">
</script>
</head>
<body>
<h1>GeeksforGeeks</h1>
<b>
How to get the Location of an
element relative<br> to the
document using jQuery/JavaScript?
</b>
<br><br>
<div id="Logo">
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200121112744/logo11.png">
</div>
<br><br>
<button type="button">Click</button>
<h4></h4>
<script>
(document).ready(function() {
("button").click(function(){
var position = ("#Logo").position();
("h4").text("Location of the Logo is: (left: "
+ position.left + ", top: " + position.top + ")");
});
});
</script>
</body>
</html>
输出: