offset和client系列
以下都是对象的属性:这些属性可读不可写,跟style有区别。style可读也可写。
这个属性使用赋值”=“ ,即可获取属性值
元素的偏移量——offset
元素的偏移量,也就是元素的位置。
offsetTop:返回的是元素距离最近开启定位的父元素顶部的距离,若没有开启定位的父元素,则是距离页面的顶部距离
offsetLeft:返回的是元素距离最近开启定位的父元素左侧的距离,若没有开启定位的父元素,则是距离页面的左侧距离
offsetWidth:返回的是元素自身的width
offsetHeight:返回的是元素自身的高度
元素可视区——client
client与offset很像,作用相似。
clientTop:返回的是元素的上边框大小
clientLeft:返回的是元素的左边框大小
clientWidth:返回的是元素自身的width 不包含border的宽度
clientHeight:返回的是元素自身的高度 不包含border的宽度
offset和client的区别
offsetWidth: width + padding + border
clientWidth:width + padding 不包含border的宽度client和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;
}
.farther {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
margin: 50px 0 0 60px;
}
.son {
width: 200px;
height: 200px;
background-color: purple;
margin-left: 100px;
border: 20px solid black;
}
.box {
width: 800px;
height: 300px;
background-color: green;
padding: 10px;
border: 10px solid orange;
}
</style>
</head>
<body>
<div class="farther">
<div class="son"></div>
</div>
<div class="box"></div>
<script>
// offset系列 元素偏移
// 动态的获取元素的位置信息
var farther = document.querySelector('.farther');
// 1.得到元素的偏移量 位置 返回的值没有单位
console.log(farther.offsetTop);
console.log(farther.offsetLeft);
// 带有定位的父级元素 返回的是当前元素距离开启定位的父级元素的距离 如果没有父亲是定位的
// 返回的是距离页面的距离
var son = document.querySelector('.son');
console.log('------offset输出:Top Left------');
console.log(son.offsetTop); // 0
console.log(son.offsetLeft); // 100 子元素在父元素中的偏移量
console.log('------client输出:Top Left------');
console.log(son.clientTop); // 返回元素的上边框
console.log(son.clientLeft); // 返回元素的左边框
// 2.返回带有定位的元素 否则body
var box = document.querySelector('.box');
console.log(box.offsetParent);
// 3.获得自身的大小 高和宽 包含padding 和 border
console.log('------offset输出:Width Height------');
console.log(box.offsetWidth);
console.log(box.offsetHeight);
console.log('------client输出:Width Height------');
console.log(box.clientWidth);
console.log(box.clientHeight);
</script>
</body>
</html>
输出结果:
配色就凑合看吧(捂脸捂脸)