获取/设置标签的的位置数据
offset()用于读取和设置offset值,相对于页面左上角的坐标(有left和top值)
position():相对于父元素左上角的位置(有left和top值)
代码示例如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery的offset和position方法</title>
<style type="text/css">
*{
margin:0;
padding: 0;
}
#box1{
width: 300px;
top: 30px;
height: 300px;
background-color: #ADFF2F;
position: absolute;
}
#box2{
width: 200px;
height: 200px;
top: 50px;
background-color: azure;
position: absolute;
}
</style>
<script type="text/javascript" src="../js/jquery-3.1.1/jquery-3.1.1.min.js" ></script>
<script type="text/javascript">
$(function(){
$("#btn4").click(function(){
var $box1 = $("#box1").offset();
// alert($box1);
console.log($box1.left,$box1.top);
var $box2 = $("#box2").offset();
console.log($box2.left,$box2.top);
var $b1 = $("#box1").position();
console.log($b1.left,$b1.top);
var $b2 = $("#box2").position();
console.log($b2.left,$b2.top);
});
$("#btn5").click(function(){
$("#box1").offset({
left:10,
top:50
});
});
});
</script>
</head>
<body>
<div id="box1">
<div id="box2"></div>
</div>
<button id="btn4">读取position和offset值</button>
<button id="btn5">设置offset值</button>
</body>
</html>