Javascript中经常使用宽高和坐标属性

1.scrollHeight/Width

scrollHeight/Width是一个只读的属性,元素的内容高度/宽度,包括因为overflow属性而不可见的部分。不能直接从css中获得。scrollHeight/Width的值除了内容高度/宽度,也包括padding值
scrollWidth相似。
图片描述css

2.scrollTop/Left

scrollLeft为例:
scrollLeft属性可以获得或者设置元素滚动到左边的像素值。注意(rtl和ltr会不一样)html

  • 假如element不可以scroll的时候,好比没有设置overflow属性。scrollLeft会被重置为0,无论你设置什么值,都不会有什么效果。(这也是不少scrollLeft失效的缘由)浏览器

  • 设置的值小于0,重置为0性能

  • 设置的值超过内容容许滚动的最大值,重置为最大值。ui

注意事项:scrollLeft属性是应用在父元素上面,而不是子元素。
其它scrollTop与scrollLeft相似。this

3. offsetHeight/Width

offsetHeight/Width是一个只读属性,返回一个元素的结构宽度,包括元素的border和padding、滚动条(若是存在的话)和css设置的高度/宽度。spa

图片描述

4.offsetTop/Left

offsetLeft为例, 返回当前元素左上角相对于HTMLElement.offsetParent节点的左边界偏移的像素值。指针

HTMLElement.offsetParent:一个只读属性,返回一个指向最近的包含该元素的定位元素。若是没有定位的元素,则 offsetParent 为最近的 table 元素或根元素(标准模式下为 html;quirks 模式下为 body)。当元素的 style.display 设置为 "none" 时,offsetParent 返回 null。offsetParent 颇有用,由于 offsetTop 和 offsetLeft 都是相对于其内边距边界的。code

例如:htm

<div style="width: 300px; border-color:blue;
  border-style:solid; border-width:1;">
  <span>Short span. </span>
  <span id="long">Long span that wraps within this div.</span>
</div>

<div id="box" style="position: absolute; border-color: red;
  border-width: 1; border-style: solid; z-index: 10">
</div>

<script>
  var box = document.getElementById("box");
  var long = document.getElementById("long");
  box.style.left = long.offsetLeft + document.body.scrollLeft + "px";
  box.style.top = long.offsetTop + document.body.scrollTop + "px";
  box.style.width = long.offsetWidth + "px";
  box.style.height = long.offsetHeight + "px";
   console.log(long.offsetParent) //offsetParent为body
</script>

offsetTop 相似的道理。

5.clientWidth/Height

clientWidth/Height是一个只读属性,对于没有css或者内联元素,其值为0。它包括内部的宽度和高度和padding,但不包括滚动条、border和margin。
图片描述

6.clientTop/Left

clientTop/Left指的是一个元素顶部/左边框的宽度。

7. 区别

摘自stackoverflow的一幅图,能够很好地看到之间的区别:

图片描述

8.clientX/Y

clientX/Y属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平/竖直坐标,不包括滚动条滚动才能显示的区域。定位的依据为浏览器窗口内容区域的左上角

9.offsetX/Y(experimental technology)

offsetX/Y 设置或者是获得鼠标相对于目标事件的父元素的内边界在X/Y坐标上的位置

10.screenX/Y

screenX/Y 相对于物理屏幕/监视器的左上角,只有你增长或减小显示器的数量或分辨率,参考点才会移动。

11.pageX/Y

pageX/Y 相对于整个渲染页面的左上角(包括经过滚动隐藏的部分),简单来讲就是<html>元素。

图片描述

参考资料

1.Element.scrollHeight
2.Element.scrollLeft
3.HTMLElement.offsetWidth
4.HTMLElement.offsetParent
5.HTMLElement.offsetLeft
6.Element.clientHeight
7.Element.clientTop
8.Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

相关文章
相关标签/搜索