jQuery offset()实例
offset()方法是jQuery内置的一个方法,用于设置或返回所选元素的偏移坐标。
语法:
$(selector).offset()
- 参数。参数不需要。
$(selector).offset({top:value, left:value})
- 参数。当设置偏移量时,该参数是必需的。
$(selector).offset( function(index, offset) )
- 参数。该方法使用函数设置偏移量。在这个方法中使用的参数是可选的。index参数用于返回设定元素的位置,offset参数用于返回选定元素的坐标。
返回值:该方法返回匹配元素的坐标。
下面的例子说明了jQuery中的offset()方法。
例子1:在下面的代码中,这将返回第一个匹配元素的坐标。
<!DOCTYPE html>
<html>
<head>
<title>The offset Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function() {
("button").click(function() {
var Geek = $("p").offset();
alert("Top coordinate: " + Geek.top +
" Left Coordinate: " + Geek.left);
});
});
</script>
<style>
div {
width: 60%;
min-height: 150px;
padding: 20px;
font-size: 25px;
border: 2px solid green;
font-weight: bold;
color:green;
}
</style>
</head>
<body>
<!-- Click on paragraph -->
<div>
<p>Welcome to GeeksforGeeks!</p>
<button>click Here!</button>
</div>
</body>
</html>
输出:

示例 2:
<!DOCTYPE html>
<html>
<head>
<title>The offset Method</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function() {
("button").click(function() {
$("p").offset({top: 100, left: 140});
});
});
</script>
<style>
div{
width: 300px;
min-height: 100px;
color:green;
font-weight: bold;
padding:20px;
font-size: 25px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<!-- Click on paragraph -->
<p>Welcome to GeeksforGeeks!</p>
<button>Click Here!</button>
</div>
</body>
</html>
输出:

极客教程