定義和用法
position() 方法返回匹配元素相對(duì)于父元素的位置(偏移)。
該方法返回的對(duì)象包含兩個(gè)整型屬性:top 和 left,以像素計(jì)。
此方法只對(duì)可見元素有效。
語法
$(selector).position()
實(shí)例
獲得 <p> 元素的當(dāng)前位置:
$(".btn1").click(function(){
x=$("p").position();
$("#span1").text(x.left);
$("#span2").text(x.top);
});
完整小例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;padding: 0;
}
#big{
width:100px;
height:100px;
position: absolute;
left: 200px;
top: 200px;
}
#box{
width:100px;
height:100px;
position: absolute;
left: 300px;
top: 300px;
/* right: 300px;
bottom: 300px; */
background: red;
margin: 20px;
border: 10px solid black;
padding: 50px;
/* display: none; */
display: block;
}
</style>
</head>
<body>
<div id="big">
<div id="box"></div>
</div>
<script src="jquery-3.2.1.js"></script>
<script>
console.log($("#box").position());
console.log($("#box").position().left);
console.log($("#box").position().top);
console.log($("#box").position().right);
console.log($("#box").position().bottom);
</script>
</body>
</html>
方法總結(jié)
1.$("#box").position()的輸出值是一個(gè)對(duì)象,{"left":xxx,"top":xxx}(就像這個(gè));$("#box").position().left的輸出值這個(gè)元素的left值(包括對(duì)該元素的定位設(shè)置為right時(shí));$("#box").position().top的輸出值這個(gè)元素的top值(包括對(duì)該元素的定位設(shè)置為bootom時(shí));而$("#box").position().right和$("#box").position().bottom的輸出值為undefined。
2.它的left和top都是相對(duì)于它的父元素而言,而不是相對(duì)于整個(gè)頁面。
3.當(dāng)給這個(gè)元素設(shè)定display:none屬性時(shí),$("#box").position()會(huì)輸出{"left":-200,"top":-200};$("#box").position().left會(huì)輸出-200(包括對(duì)該元素的定位設(shè)置為right時(shí));$("#box").position().top會(huì)輸出-200(包括對(duì)該元素的定位設(shè)置為bootom時(shí));而$("#box").position().right和$("#box").position().bottom的輸出值依然為undefined。
4.當(dāng)給這個(gè)元素的父元素設(shè)定display:none屬性時(shí),當(dāng)給這個(gè)元素設(shè)定display:none屬性時(shí),$("#box").position()會(huì)輸出{"left":0,"top":0};$("#box").position().left會(huì)輸出0(包括對(duì)該元素的定位設(shè)置為right時(shí));$("#box").position().top會(huì)輸出0(包括對(duì)該元素的定位設(shè)置為bootom時(shí));而$("#box").position().right和$("#box").position().bottom的輸出值依然為undefined。
5.當(dāng)不給這個(gè)元素設(shè)定position:absolute(或者position:fixed),以及不給這個(gè)元素設(shè)定position值(或者設(shè)定position:relative)時(shí),$("#box").position()會(huì)輸出{"left":0,"top":0};$("#box").position().left會(huì)輸出0(包括對(duì)該元素的定位設(shè)置為right時(shí));$("#box").position().top會(huì)輸出0(包括對(duì)該元素的定位設(shè)置為bootom時(shí));而$("#box").position().right和$("#box").position().bottom的輸出值依然為undefined。
綜上:JQuery中的position()方法可以獲取匹配元素相對(duì)父元素的偏移,返回的對(duì)象包含兩個(gè)整型屬性:top 和 left。(若想獲取匹配元素在當(dāng)前視口的相對(duì)偏移可以使用JQuery中的offset()方法)