元素偏移量offset的学习
一、offset概述
offset就是偏移量,使用offset系列相关属性可以动态地得到该元素的位置(偏移)、大小等。
- 获得元素距离带有定位父元素地位置;
- 获得元素自身的大小(宽度、高度);
- 返回的数值都不带单位。
offset系列常用属性:
举例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.parent {
width: 500px;
height: 500px;
margin: 100px auto;
background-color: red;
border: 10px solid #000;
overflow: hidden;
}
.child {
width: 300px;
height: 300px;
border: 1px solid #000;
padding: 10px;
margin: 50px 90px;
background-color: green;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
<script>
var child = document.querySelector('.child');
var html = '';
html += "offsetWidth=" + child.offsetWidth + "<br>";
html += "offsetHeight=" + child.offsetHeight + "<br>";
html += "offsetTop=" + child.offsetTop + "<br>";
html += "offsetLeft=" + child.offsetLeft;
child.innerHTML = html;
</script>
</body>
</html>
运行效果图如下:
offset与style的区别
offset:
- offset可以得到任意样式表中的样式值;
- offset系列获得的数值是没有单位的;
- offsetWidth包含padding+border+width;
- offsetWidth等属性是只读属性,只能获取不能赋值;
- 要想获取元素大小位置,用offset更合适。
style:
- style只能得到行内样式表中的样式值;
- style.width获得的是带由单位的字符串;
- style.width获得的不包含padding和border属性;
- style.width是可读写属性,可以获取也可以赋值;
- 要想给元素更改值,需要用style来改变。
例如:
<!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>
.box {
width: 200px;
height: 200px;
background-color: pink;
padding: 10px;
</style>
</head>
<body>
<div class="box" style="width: 200px;"></div>
<script>
// offset与style的区别
var box = document.querySelector(' .box');
console.log(box.offsetWidth);
console.log(box.style.width);
// box.offsetWidth = '300px';
box.style.width = '300px';
</script>
</body>
</html>