测试的HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body, html {
margin: 0;
}
#box {
overflow: scroll;
position: absolute;
width: 100px;
height: 100px;
margin: 20px;
padding: 10px;
border: 1px solid red;
color: #fff;
background: #000;
}
#outer{
border: 2px solid yellow;
position: relative;
width: 200px;
height: 200px;
background: green;
padding-top: 10px;
padding-left: 10px;
}
</style>
</head>
<body>
<div id="outer">
<div id="box">
我是内容
<br>
<br>
<br>
<br>
s
s
s
s<br>
<br>
s
s
s
s<br>
<br>
s
s<br>
<br>
s
s
s
s
s
</div>
</div>
</body>
</html>
<script>
// clientWidth \ clientHeight \ clientTop \ clientLeft
console.log(box.clientWidth) // =>120 content.width + padding-left + padding-right
console.log(box.clientHeight)// =>120 content.height + padding-top + padding-bottom
console.log(box.clientTop)// =>1 border-top
console.log(box.clientLeft)// =>1 border-left
console.log('===============================================')
// offsetWidth \ offsetHeight \ offsetTop \ offsetLeft
console.log(box.offsetWidth)// =>122 width + padding-left + padding-right + border-left + border-right
console.log(box.offsetHeight)// =>122 height + padding-top + padding-bottom + border-top + border-bottom
console.log(box.offsetTop)// =>20 (offsetParent.padding-top) + margin-top
/*如果是父级元素是 body 的话 也会算上html的padding-top*/
console.log(box.offsetLeft)// =>20 (offsetParent.padding-left) + margin-left
/*如果是父级元素是 body 的话 也会算上html的padding-left*/
console.log(box.offsetParent)// outer元素 获取父元素
console.log('==========================================')
// scrollWidth \ scrollHeight \ scrollTop \ scrollLeft
console.log(box.scrollWidth)// =>120 width + padding-left + padding-right如果内容超出 也会进行计算
console.log(box.scrollHeight)// =>186 width + padding-left + padding-right + 内容超出
console.log(box.scrollTop)// =>0 滚动条距离顶部的高度
console.log(box.scrollLeft)// =>0 滚动条距离左边的长度
</script>