JS动画的三大家族包括:offset/scroll/client,这章讲offset,以及与其相关的匀速动画
offset 家族的组成
js中有一套方便的获取元素尺寸的办法就是offset家族。offset家族包括:
-
offsetWidth
-
offsetHight
-
offsetLeft
-
offsetTop
-
offsetParent
offsetWidth 和 offsetHight
offsetWidth
和 offsetHight
:获取元素的宽高 + padding + border,不包括margin。如下:
- offsetWidth = width + padding + border
- offsetHeight = Height + padding + border
- 返回的都是一个数字不带px,可直接进行计算
这两个属性,他们绑定在了所有的节点对象上,获取节点对象之后,只要调用这两个属性,我们就能够获取元素节点的宽和高
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid #000;
margin: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var div1 = document.getElementsByTagName("div")[0];
console.log(div1.offsetHeight); //打印结果:140(100+20+20)
console.log(typeof div1.offsetHeight); //打印结果:number
</script>
</body>
</html>
offsetParent
offsetParent
:获取当前元素的定位父元素
- 获取离他最近的开启了定位的祖先元素
- 如果所有的祖先元素都没有开启定位 (position为absolute、relative、fixed),那么返回值为body
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="box1" style="position: absolute;">
<div class="box2" style="position: fixed;">
<div class="box3"></div>
</div>
</div>
<script>
var box3 = document.getElementsByClassName("box3")[0];
console.log(box3.offsetParent.className); // box2
</script>
</body>
</html>
offsetLeft 和 offsetTop
offsetLeft
:当前元素相对于其定位父元素的水平偏移量。
offsetTop
:当前元素相对于其定位父元素的垂直偏移量。
备注:会无视参考的那个父元素的 padding,在border内侧为参考点(类似绝对定位特性)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box1 {
width: 200px;
height: 100px;
padding: 50px;
margin: 10px;
position: relative;
border: 10px solid #000;
background-color: #bfa;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
<script>
var box2 = document.getElementsByClassName("box2")[0];
//offsetTop和offsetLeft,盒子本身不需要开启定位就可查询
console.log(box2.offsetLeft); //50 因为padding是50
console.log(box2.style.left); //'' 空字符串,没设置这个left属性
//style方式,盒子本身必须开启定位才能查询和修改,不开启也能查但没意义
box2.style.left = '10px'; // 在行内查询或修改
console.log(box2.offsetLeft);