JS动画的主要内容如下:
1、三大家族和一个事件对象:
2、动画(闪现/匀速/缓动)
3、冒泡/兼容/封装
今天来讲一下offset,以及与其相关的匀速动画。
offset的中文是:偏移,补偿,位移。
js中有一套方便的获取元素尺寸的办法就是offset家族。offset家族包括:
下面分别介绍。
offsetWidth
和 offsetHight
:获取元素的宽高 + padding + border,不包括margin。如下:
这两个属性,他们绑定在了所有的节点元素上。获取元素之后,只要调用这两个属性,我们就能够获取元素节点的宽和高。
举例如下:
<!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
获取的是最近的那个父元素。
offsetParent
获取的是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);
</script>
</body>
</html>
打印结果:
offsetLeft
:当前元素相对于其定位父元素的水平偏移量。
offsetTop
:当前元素相对于其定位父元素的垂直偏移量。
备注:从父亲的 padding 开始算起,父亲的 border 不算在内。
举例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box1 {
width: 300px;
height: 300px;
padding: 100px;
margin: 10px;
position: relative;
border: 100px solid #000;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
/*position: absolute;*/
/*left: 10px;*/
/*top: 10px;*/
}
</style>
</head>
<body>
<div class="box1">
<div class="box2" style="left: 10px"></div>
</div>
<script>
var box2 = document.getElementsByClassName("box2")[0];
//offsetTop和offsetLeft
console.log(box2.offsetLeft); //100
console.log(box2.style.left); //10px
</script>
</body>
</html>