三大家族
一、offset家族
1.概念
offset自己的,用来获取元素尺寸
2.属性
(1)offsetWidth
和offsetHeight
获取自身的宽度和高度,包括内容、边框和内边距
offsetWidth = content + border + padding
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
#box{
width: 200px;
height: 150px;
background-color: red;
padding: 10px;
border: 5px solid #000;
margin: 20px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
console.log(box.offsetWidth);//230
console.log(box.offsetHeight);//180
console.log(box.style.width, box.style.height);//取不到结果,style只能拿行内的
};
</script>
</body>
</html>
.style.width
<body>
<div id="box" style="width: 200px; height: 300px;"></div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
console.log(box.style.width, box.style.height);
//只能拿到内容的宽度
//200px,300px
};
</script>
</body>
(2)offsetLeft
和offsetTop
距离第一个有定位的父盒子左边和上边的距离(从里往外找)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>练习</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
#father{
position: relative;
width: 400px;
height: 400px;
background-color: red;
margin: 40px;
}
#box{
position: absolute;
width: 200px;
height: 150px;
background-color: blue;
padding: 10px;
border: 5px solid #000;
margin-left: 30px;
}
</style>
</head>
<body>
<div id="father">
<div id="box"></div>
</div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
console.log(box.offsetLeft, box.offsetTop);
//30,0
};
</script>
</body>
</html>
如果父盒子没有定位,则最终以body为准
(3)offsetParent
返回当前对象的父级(带有定位)的盒子,可能父亲、也可能是爷爷······(从里往外找)
<body>
<div id="yeye" style="position: relative">
<div id="father" style="position: relative">
<div id="box"></div>
</div>
</div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
console.log(box.offsetParent);
//是father,两个都有定位,但是是从里往外找的
};
</script>
</body>
如果父级盒子没有定位,则最终以body为准
.parentNode
<body>
<div id="yeye" >
<div id="father">
<div id="box"></div>
</div>
</div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
console.log(box.parentNode);//无论有没有定位,拿到的都是父节点
};
</script>
(4)stylexxx
和offsetxxx
的区别
①style只能拿行内的;而offset可以获取到所有的
②style可以返回没有定位的;而offset只能返回有定位的(除去offsetWidth
和offsetHeight
)
③style返回的是字符串,除了数字之外还有单位:px
;而offset返回的是数字
④style是可读可写的;而offset只是可读的
offsetxxx
<body>
<div id="box" style="width: 100px; height: 100px;"></div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
box.offsetWidth = 200;
console.log(box.offsetWidth);
//100,不能编辑,也就是不能改变
};
</script>
</body>
stylexxx
<body>
<div id="box" style="width: 100px; height: 100px;"></div>
<script>
window.onload = function (ev) {
var box = document.getElementById('box');
box.style.width = 200 +'px';
console.log(box.style.width);
//200px,可以编辑
};
</script>
</body>
⑤如果没有给当前元素指定过top样式,则style.top
返回的是空字符串