jQuery position()实例
position()方法是jQuery内置的方法,用于查找第一个匹配的元素相对于其父元素在DOM树中的位置。
语法:
$(selector).position()
参数:该方法不包含任何参数。
返回值:该方法返回第一个匹配元素的位置。
下面的例子说明了jQuery中的position()方法。
示例:
<!DOCTYPE html>
<html>
<head>
<title>The position 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 x = $("p").position();
alert("Top position: " + x.top);
});
});
</script>
<style>
div {
width: 350px;
height: 100px;
font-weight: bold;
padding:20px;
font-size: 25px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>GeeksforGeeks.</p>
<!-- Click on this button -->
<button>Click Here!</button>
</div>
</body>
</html>
输出:
在点击按钮之前。
点击按钮后。