三种表格展示
offset系列
offset | 获取 |
---|
offsetWidth | width (宽度)+ 左右的padding(内边距) + 左右的border(边框) |
offsetHeight | height (高度)+ 上下的padding(内边距) + 上下的border边框) |
1、父元素有定位
offset | 获取 |
---|
offsetTop | 元素距离父元素上侧的距离 |
offsetLeft | 元素距离父元素左侧的距离 |
2、父元素没有定位
offset | 获取 |
---|
offsetTop | 元素距离上侧浏览器的距离 |
offsetLeft | 元素距离左侧浏览器的距离 |
client系列
client | 获取 |
---|
clientWidth | width (宽度)+ 左右的padding(内边距) |
clientHeight | height(高度)+ 上下的padding(内边距) |
clientTop | 上边框 border-top |
clientLeft | 左边框 border-left |
scroll系列
scroll | 获取 |
---|
scrollWidth | width (宽度)+ 滚动条滚动的距离 |
scrollHeight | height(高度)+ 滚动条滚动的距离 |
scrollTop | 上下滚动条滚动的距离 |
scrollLeft | 左右滚动条滚动的距离 |
源码解析
css样式
<style>
* {
padding: 0;
margin: 0;
}
#parent {
position: relative;
margin-left: 100px;
width: 400px;
height: 400px;
border: 10px solid pink;
}
#child {
margin-left: 50px;
width: 200px;
height: 200px;
border: 5px solid red;
padding: 10px;
background-color: bisque;
}
#small {
margin-top: 100px;
width: 300px;
height: 300px;
background-color: bisque;
overflow: auto;
}
#big {
width: 500px;
height: 500px;
}
</style>
html创建
<body>
<div id="parent">
<div id="child"></div>
</div>
<div id="small">
<div id="big">
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
</div>
</div>
</body>
js部分解析
var parent = document.getElementById("parent");
var child = document.getElementById("child");
console.log(child.offsetWidth);
console.log(child.offsetHeight);
console.log(child.offsetLeft);
console.log(child.offsetTop);
console.log(child.clientWidth);
console.log(child.clientHeight);
console.log(child.clientTop);
console.log(child.clientLeft);
var small = document.getElementById("small");
console.log(small.scrollWidth);
console.log(small.scrollHeight);
console.log(small.scrollTop);
console.log(small.scrollLeft);
small.scrollLeft = 200
small.onscroll = function () {
console.log(small.scrollTop);
console.log(small.scrollLeft);