jquery獲取當(dāng)前元素的位置,并且是相對(duì)于文檔的位置。我們可以使用jQuery offset()方法來(lái)實(shí)現(xiàn)。offset()方法僅適用于可見(jiàn)元素。
下面我們結(jié)合簡(jiǎn)單的代碼,給大家介紹jquery獲取當(dāng)前元素的位置的方法。
代碼示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jquery獲取當(dāng)前元素的位置</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
#box{
width:150px;
height:100px;
background: orange;
margin: 150px 100px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/JAVAscript">
$(function() {
$("button").click(function(){
var offset = $("#box").offset();
alert("盒子的當(dāng)前位置為: (left: " + offset.left + ", top: " + offset.top + ")");
});
});
</script>
</head>
<body>
<button type="button">獲取位置</button>
</body>
</html>
offset() 方法返回或設(shè)置匹配元素相對(duì)于文檔的偏移(位置)。
該.offset()方法允許我們檢索相對(duì)于文檔的元素的當(dāng)前位置(特別是其邊界框,其排除邊距)。與此對(duì)比.position(),它檢索相對(duì)于偏移父項(xiàng)的當(dāng)前位置。將新元素放置在現(xiàn)有元素之上進(jìn)行全局操作(特別是實(shí)現(xiàn)拖放)時(shí).offset()更有用。
.offset()返回包含屬性top和的對(duì)象left。
獲取當(dāng)前元素的位置,結(jié)果如下:
本篇文章就是關(guān)于jquery獲取當(dāng)前元素的位置的方法介紹,也很簡(jiǎn)單,希望對(duì)需要的朋友有所幫助!






