首页 > 技术文章 > offset & client & scroll

Grani 2018-09-18 14:21 原文

页面中所有标签都是元素(element),html标签是根元素,元素可看出是对象

页面中所有内容都是节点(node),所以标签、属性、文本都是节点,而文本包括文字回车换行空格

在DOM对象上有个 properties 属性,offset、client和scroll三大系列都在properties里

offset

DOM对象上有offsetLeftoffsetTopoffsetWidthoffsetHeightoffsetParent五个属性

 offsetWidth

 返回元素的宽度

(content+padding+border)

 offsetHeight

 返回元素的高度

(content+padding+border)

 offsetLeft  返回元素的水平偏移位置
 offsetTop  返回元素的垂直漂移位置
 offsetParent  返回元素的偏移容器

 

 

 

 

 

 

 

 

 

标准流中,offsetLeft和offsetTop的偏移是相对于document来说的,也就是距离浏览器窗口左边的距离

<head>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background: #2c323b;
        }
    </style>
</head>
<body>
<div id="box">
</div>
<script>
    var box = document.getElementById('box')
    console.log(box.offsetLeft)
</script>
</body>

由于body有默认的margin,所以此时box的offsetLeft为8px

给body设置样式

body {
  border:10px solid #3385ff;
  padding:30px;
  margin:40px;
}

box的offsetLeft变为为80px

 

标准流时,元素的offsetLeft为:父级margin+border+padding + 自己margin

脱标时父级或祖先级元素没有定位,则元素offsetLeft为:自己的left+margin

若父级或祖先元素有定位,那个元素就是偏移容器(offsetParent),offsetLeft为:偏移容器的border + 自己的left + margin


 client

 clientWidth  返回元素的可见宽度
 clientHeight  返回元素的可见高度
 clientLeft  返回元素左边框宽度
 clientTop  返回元素上边框宽度

 

 

 

 

 

 

clientWidth,元素可视区域的宽度,不包括边框

clientX和clientY是鼠标事件处理参数对象里的属性,事件触发时返回鼠标指针在浏览器窗口的坐标


scroll

 scrollWidth  返回元素内容的宽度
 scrollHeight  返回元素内容的高度
 scrollLeft  返回元素向左卷曲的距离
 scrollTop  返回元素向上卷曲的距离

 

 

 

 

 

 

scrollWidth,元素没内容或内容宽度小于元素宽度,则为元素宽度

推荐阅读