offset就是偏移量 用offset系列的相关属性可以动态的得到该元素的位置(偏移)、大小
1.获得元素距离 带有定位的父元素的位置
2.获得元素自身的大小(宽度、高度)
3.返回的元素不带单位
element.offsetTop返回元素距离顶部的距离
element.offsetleft返回元素距离左边的距离
<style>
/* 如果不加这个 father距离左边的距离是108px */
*{
margin: 0;
padding: 0;
}
.father{
position: relative;
width: 150px;
height: 150px;
background-color: pink;
margin: 100px;
}
.son{
width: 100px;
height: 100px;
background-color: red;
margin-left: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
var father=document.querySelector('.father');
var son=document.querySelector('.son');
console.log("father.offsetTop="+father.offsetTop);
console.log("father.offsetleft="+father.offsetLeft);
// 如果父盒子不加定位,那么获取的就是子盒子到浏览器边缘的距离
console.log(son.offsetLeft);//120
// 如果给父盒子添加绝对定位或者说是相对定位
// 则得到的距离是子盒子左边缘到父盒子左边缘的距离20
</script>
</body>
元素.offsetParent 获取父亲元素,如果父级没有定位,就返回body
console.log(son.offsetParent);//
把father的定位去掉
获取元素的宽高
元素.offsetHeight / offsetWidth=width+paidding+border
<style>
.box{
height: 200px;
background-color: aqua;
padding: 10px;
/* margin: 100px; */
border: 10px solid red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box');
console.log(box.offsetHeight);//200
console.log(box.offsetWidth);//1022
</script>
</body>