DOM元素获取位置信息各类方法图示

本文详细介绍了DOM元素获取位置信息的各种方法,包括getBoundingClientRect、Element.scrollHeight、Element.clientHeight、HTMLElement.offsetTop和Element.scrollTop。getBoundingClientRect返回包含元素内容、边框和padding的最小矩形;scrollHeight包含所有内容的高度,包括不可见部分;clientHeight表示元素的可视区域内content和padding的高度;offsetTop则表示元素相对于offsetParent顶部的距离;scrollTop属性用于获取或设置元素垂直滚动的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getBoundingClientRect

  • 用法

    domRect = element.getBoundingClientRect();
    
  • 图解
    在这里插入图片描述

    The returned value is a DOMRect object which is the smallest rectangle which contains the entire element, including its padding and border-width.
    返回值是一个DOMRect对象,该对象是包含这个元素的最小矩形,包括了content + padding + border

    The width and height properties of the DOMRect object returned by the method include the padding and border-width, not only the content width/height.
    该对象内的 width、height 包含 content + padding + border,而不仅是 content

Element.scrollHeight

  • 用法

    elemScrollHeight = element.scrollHeight;
    
  • 图解

在这里插入图片描述

The Element.scrollHeight read-only property is a measurement of the height of an element’s content, including content not visible on the screen due to overflow.

scrollHeight是一个仅读属性,它包括了元素内容的不可见部分的高度 (元素整体的content + padding + scrollbar)

Element.clientHeight

  • 用法

    var intElemClientHeight = element.clientHeight;
    
  • 图解
    在这里插入图片描述

The Element.clientHeight is read-only property, it’s the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present).

clientHeight 是仅读属性,包括元素 (可见部分) 的content + padding,不包括border、margin、scrollbar

HTMLElement.offsetTop

  • 用法

    topPos = element.offsetTop;
    
  • 图解

    在这里插入图片描述

The HTMLElement.offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent node.

offsetTop 是仅读属性,表示该元素的边框外侧距最近offsetParent边框内侧之间的距离

注:offsetParent并不一定是父元素,而是最近的相对定位的祖先,如果没有则是body

Element.scrollTop

  • 用法

    var intElemScrollTop = someElement.scrollTop;
    
  • 图解
    在这里插入图片描述

The Element.scrollTop property gets or sets the number of pixels that an element’s content is scrolled vertically.

scrollTop 是可读写的属性,它表示一个可滚动元素垂直方向上翻滚上去的内容高度
注:html的scrollTop 与 window.scrollX 相同

注: 以上属性每种只举了其中一个说明,例如height,但应该知道width也是类似的即可

参考


Element.getBoundingClientRect
Element.scrollHeight
Element.clientHeight
HTMLElement.offsetTop
Element.scrollTop

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tanleiDD

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值