Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery position()

通过jQuery position()方法,您可以检索元素相对于父元素的当前位置。它返回第一个匹配元素的位置。此方法返回具有两个属性的对象:像素的顶部和左侧位置。
注意: jQuery position()方法与jQuery offset()方法不同,因为position()方法检索元素相对于父元素的当前位置,而offset()方法)方法检索相对于文档的当前位置。
注意:当您要将一个新元素放置在同一个包含DOM元素的另一个元素附近时,position()方法会更加有用。
语法:
$(selector).position()

jQuery position()方法的示例

让我们以一个示例来演示jQuery position()方法。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var x = $("p").position();
        alert("Top position: " + x.top + " Left position: " + x.left);
    });
});
</script>
</head>
<body>
<p>You are reading this tutorial on lidihuo.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>
输出:

You are reading this tutorial on lidihuo.com

jQuery position() 另一个示例

<!DOCTYPE html>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var position = $(this).position();
$("#lresult").html("left position: <span>" + position.left + "</span>.");
$("#tresult").html("top position: <span>" + position.top + "</span>.");
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="lresult"> </span>
<span id="tresult"> </span>
<div style="background-color:#ffd700"></div>
<div style="background-color:#030303"></div>
<div style="background-color:#473c8b"></div>
<div style="background-color:#ee82ee"></div>
</body>
</html>
输出:

Click on any square:

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4