1.clientTop、clientLeft获取的是上边框、左边框的宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>location</title>
<style>
.content {
position: relative;
height: 600px;
width: 600px;
margin: 0 auto;
background-color: pink;
overflow: hidden;
}
.father {
margin: 50px auto;
height: 450px;
width: 450px;
background-color: #ccc;
overflow: hidden;
}
.son {
border-top: 10px solid red;
border-right: 20px solid red;
border-bottom: 30px solid red;
border-left: 40px solid red;
padding: 10px;
margin: 50px;
height: 300px;
width: 300px;
background-color: #000;
}
</style>
<script>
window.onload = function() {
let sonDiv = document.querySelector('.son');
console.log('clientTop: ' + sonDiv.clientTop);
console.log('clientLeft: ' + sonDiv.clientLeft);
}
</script>
</head>
<body>
<div class="content">
<div class="father">
<div class="son"></div>
</div>
</div>
</body>
</html>
这里son盒子的上边框是10px,左边框是40px:
2.clientWidth、clientHeight会计算标签的内边距+内容的宽度或者高度,同样是上面的样式,打印一下son盒子的这两个属性:
window.onload = function() {
let sonDiv = document.querySelector('.son');
console.log('clientWidth: ' + sonDiv.clientWidth);
console.log('clientHeight: ' + sonDiv.clientHeight);
}
这里son盒子的内边距为10px,内容为300px,结果为300+10*2=320px:
这两个属性与offsetWidth、offsetHeight的区别是offset属性包含了边框的宽度.