offset家族
- 1.offset属性家族:获取元素真实的宽高和位置
- offsetWidth、offsetHeight、offsetParent、offsetLeft、offsetTop
- 2.之前学习的通过style属性获取宽高的特点
- 1.只能获取行内的宽高
- 2.获取到的值是一个string类型,并且带px
- 3.获取到的只有宽高,不包含padding、border(总结就是行内写的是什么,获取的就是什么)
- 4.既可以读取,也可以设置
- 3.offsetWidth与offsetHeight:获取的是元素的实际宽高 = width + border + padding
- 1.可以获取行内及内嵌的宽高
- 2.获取到的值是一个number类型,不带单位
- 3.获取的宽高包含border和padding
- 4.只能读取,不能设置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>offset家族</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
left: 100px;
top: 100px;
background-color: rgb(226, 15, 79);
width: 100px;
height: 100px;
border: 50px solid #6cf;
padding: 50px;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="box">我是一名保安</div>
</body>
<script>
// 获取元素
const box = document.querySelector(".box");
// 行外样式: style拿不到
// offset家族
// 真实宽高: offsetWidth,offsetHeight, 组成: border + padding + content
// 真实偏移: offsetLeft,offsetTop, 组成: 定位 + margin
// 拿到的结果是数字
console.log(box.offsetWidth); // 300
console.log(box.offsetHeight); // 300
console.log(box.offsetLeft, box.offsetTop); // 200 100
</script>
</html>
offsetParent
offsetParent:获取最近的定位父元素 (自己定位参照的父元素)
注意点:
1.如果元素自身是固定定位(fixed),则定位父级是null
2.如果元素自身是非固定定位,并且所有的父元素都没有定位,那么他的定位父级是body
3.body的定位父级是null
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>offset家族 - 定位父级</title>
<style>
* {
margin: 0;
padding: 0;
}
.parent {
position: relative;
left: 100px;
width: 200px;
height: 200px;
background-color: pink;
overflow: hidden;
}
.son {
width: 150px;
height: 100px;
background-color: purple;
margin-top: 100px;
margin-left: 50px;
}
span {
display: inline-block;
width: 100px;
height: 100px;
background-color: greenyellow;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="parent">
<div class="son">
<span>马云</span>
</div>
</div>
<script>
// offsetParent: 定位父级, 唯一价值: 用来计算offsetLeft和offsetTop
// offset偏移: 是距离定位父级的偏移
const span = document.querySelector("span");
console.log(span.offsetLeft);
// 150 = left 100 + 父元素son的margin 50
// 偏移不是相对于son父元素,而是相对于定位父级: parent
// 元素.offsetParent 可以找到定位父级
console.log(span.offsetParent);
// 顶级定位元素: body
console.log(span.offsetParent.offsetParent);
</script>
</body>
</html>