注明:
- div#test1的边框是深红色部分,阴影区域是padding,高亮选中部分是content-width。黄色部分是margin.
- div.box的边框是蓝色,浅紫色是padding.
代码
<style>
.box {
position: relative;
padding:20px;
background-color: rgb(206, 205, 255);
border:solid 10px blue;
}
#test1{
margin:20px;
width:200px;
height:200px;
padding:50px;
border:solid 20px red;
overflow: scroll;
background-color: aquamarine;
}
</style>
<div class="box">
<div id="test1"></div>
</div>
<script type="text/babel">
const test1Dom = document.getElementById('test1');
console.log('offsetParent',test1Dom.offsetParent);
console.log('offsetTop', test1Dom.offsetTop);
console.log('offsetLeft', test1Dom.offsetLeft);
</script>
注意:当块状元素嵌套关系时,假设父元素没有设置border或padding值或overflow:hidden,那么子元素的margin值不生效。
HTMLElement.offsetParent
要想明白offsetTop和offsetLeft,必须先了解offsetParent,因为前两者是相对于offsetParent元素内边距边界的偏移量。
HTMLElement.offsetParent是一个只读属性,返回一个指向最近的包含该元素的定位元素或者最近的table,td,th,body元素。 当元素的display设置为none时,offsetParent返回null.
上述代码中,div.box
是距离div#test1
最近的定位元素,所以div#test1
的offsetParent是div.box
。
HTMLElement.offsetTop
HTMLElement.offsetTop 是一个只读属性,返回当前元素上外边框相对于HTMLElement.offsetParent节点上内边框偏移的像素值。
上述代码中,offsetTop是从div#test1
的上外边框(即包含边框)到div.box
的上内边框(及不包含边框,包含padding)。
HTMLElement.offsetLeft
HTMLElement.offsetLeft 是一个只读属性,返回当前元素左外边框相对于HTMLElement.offsetParent节点左内边框偏移的像素值。
上述代码中,offsetLeft是从div#test1
的左外边框(即包含边框)到div.box
的左内边框(及不包含边框,包含padding)。
Element.scrollTop
Element.scrollTop属性可以获取或设置
一个元素的内容垂直滚动的像素数。
一个元素的scrollTop值是这个元素的内容顶部
到它的视口可见内容
的距离。即Element的内容向上滚动的像素数,是一个整数,不带单位。 可以设置。
Element.scrollLeft
Element.scrollLeft属性可以读取或设置元素滚动条到元素左边的距离。scrollLeft
可能会是一个小数。