JS盒模型

一 概念

# JS盒模型 *********

#### 1、width | height

- parseInt(getComputedStyle(ele, null).getPropertyValue('width'))
- parseInt(getComputedStyle(ele, null).getPropertyValue('height'))

#### 2、padding + width | padding + height

- clientWidth
- clientHeight

#### 3、border + padding + width | border + padding + height

- offsetWidth
- offsetHeight

#### 4、结合绝对定位,距离最近定位父级的Top | Left

- offsetTop
- offsetLeft

 

二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>就是盒模型</title>

<style type="text/css">
.sup {
width: 200px;
height: 200px;
padding: 30px;
border: 5px solid black;
background-color: orange;
margin: 20px;
position: relative;
}

.sub {
width: 100px;
height: 100px;
padding: 20px;
border: 5px solid black;
background-color: red;
position: absolute;
top: 0;
left: 20px;
}
</style>
</head>
<body>
<div class="sup">
<div class="sub"></div>
</div>
</body>
<script type="text/javascript">
var sup = document.querySelector('.sup');
// 盒子content的width
var width = parseInt(getComputedStyle(sup, null).width);
console.log(width);

// 盒子padding+width => 子级的可活动范围
var p_width = sup.clientWidth;
console.log(p_width);

// 盒子border+padding+width => 可视区域
var b_p_width = sup.offsetWidth;
console.log(b_p_width);

// 盒子距离定位父级的top,left
var sup_top = sup.offsetTop;
var sup_left = sup.offsetLeft;
console.log(sup_top);
console.log(sup_left);


var sub = document.querySelector('.sub');
// 父级定位(relative)后,子级活动区域为父级的client(padding+width)区域
var sub_top = sub.offsetTop;
var sub_left = sub.offsetLeft;
console.log(sub_top);
console.log(sub_left);

</script>
</html>

posted @ 2018-10-23 15:23  不沉之月  阅读(79)  评论(0编辑  收藏  举报