美文网首页
js 元素的client/offsetwidth和client/

js 元素的client/offsetwidth和client/

作者: codeflame | 来源:发表于2018-09-07 18:57 被阅读0次

    来自stackoverflow。
    总而言之,js中client/offset开头的height、width、left、top与css中的都有区别。



    下面算是属于元素“内部的几何属性”

    clientHeight

    Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, but it does not include the scrollBar, border, and the margin.

    值为整数,单位px。其包括内边距,但不包括滚动条、边框、外边距。

    clientLeft

    clientLeft = left border + left scrollbar width (if present). (block level elements -only!)
    clientLeft =元素的左边框宽度+左边滚动条宽度(如果有的话)。注意只有块级元素该属性有效

    offsetHeight:

    Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, scrollBar, and the border, but does not include the margin.

    值为整数,单位px。其包括内边距、滚动条、边框,但不包括外边距。
    So, offsetHeight includes scrollbar and border, clientHeight doesn't.
    也就是offsetHeight在clientHeight基础之上,多算了上下的滚动条和边框。



    下面这算是属于元素“外部的几何属性”,与offsetParent相关
    offsetLeft = position left+margin from the first positioned parent left edge.
    offsetLeft =元素left和左外边距(就是css的:left和margin-left),到外面第一个“适合”父元素border内侧的距离。

    这里的“适合”的父元素(offsetParent)满足下面3个条件之1即为适合:
    1.CSS-positioned设置为 absolute or relative or fixed(不为static即可)
    2.是这些元素: <td>, <th>, <table>,
    3.是<body>元素
    该元素的offsetParent为null的几种情况:
    1.该元素使用了display:none(此时offsetLeft为0,相当于不存在了)
    2.该元素是<body> 或 <html>(此时offsetLeft为0,因为它就是最外层)
    3.该元素使用了position:fixed(此时offsetLeft以<body>为父边界计算)


    后记

    提一下容易混肴的几个量度:
    css的left、margin-left、width;js元素对象属性的offsetWidth、clientWidth;js中event对象的offsetX, clientX, pageX, screenX, layerX。
    可以参考下我翻译的另外几篇:
    css border-box与content-box的不同点
    js event的各个坐标属性
    js 元素的client/offsetwidth和client/offsetleft相关属性
    上面3篇有些凌乱分散,有能力的直接阅读这篇:Element size and scrolling

    相关文章

      网友评论

          本文标题:js 元素的client/offsetwidth和client/

          本文链接:https://www.haomeiwen.com/subject/ujgcgftx.html