JS中的位置和宽度:clientWidth、offsetWidth、scrollWidth,clientTop和clientLeft等区别

317 阅读1分钟

1.clientWidth,clientheight, clientTop和clientLeft:

a:clientWidth的客户宽

    clientWidth = width+左右padding

b:clientHeigh客户高

    clientHeigh = height + 上下padding 

c:clientTop

    clientTop = boder.top   上边框的宽度

d:clientLeft

   clientLeft = boder.left   左边框的宽度

有内容有滚动条还需要减去滚动条相应的px值,因为滚动条占位置。

如果要获取元素的宽高没有滚动条就用clientWidth,clientHeigh。

2.offsetWidth和offsetHight,offsetTop和offsetLeft:

a:offsetWidth偏移宽

   width + 左右padding + 左右boder

b:offsetHeith偏移高

  height + 上下padding + 上下boder

c:offsetTop

 当前元素的上边框,外边距到最近的已定位父元素上边框内边距的距离,
 如果父元素都没有定位,则分别是到body顶部和左边的距离

d:offsetLeft

 当前元素的左边框,外边距到最近的已定位父元素左边框内边距距离,
 如果父元素都没有定位,则分别是到body顶部和左边的距离

如果要获取元素实际占位就用offsetWidth,offsetHeith

3:scrollWidth和scrollHeight,scrollTop和scrollLeft

a:scrollWidth滚动宽

 实际内容的宽加上左右padding值

b:scrollHeight滚动高

 实际内容的高加上左右padding值

c:scrollTop

 元素内容的顶部到可视区域顶部的距离。

d:scrollLeft

 元素内容的左端到可视区域左端的距离.

如果要获取滚动条内部空间就用scrollWidth,scrollHeight