美文网首页
css offsetWidth,clientWidth,scro

css offsetWidth,clientWidth,scro

作者: Peter_2B | 来源:发表于2022-12-08 15:23 被阅读0次
  • clientWidth: width(内容宽度) + 左右padding - 滚动条宽度;
  • offsetWidth: width(内容宽度) + 左右padding + 左右border宽度;
  • scrollWidth: width(内容宽度) + 左右padding + 不加左右border宽度 + 而是加溢出的宽度;
    <style>
        .wrapper {
            width: 650px;
            height: 100px;
            border: 10px solid green;
            overflow: auto;
        }

        .wrapper .cell {
            display: inline-block;
            width: 200px;
            height: 100px;
            border: 1px solid black;
            margin-right: 10px;
            margin-bottom: 20px;
            box-sizing: border-box;
        }
    </style>
    <div class="wrapper">
        <div class="cell">1</div>
        <div class="cell">2</div>
        <div class="cell">3</div>
        <div class="cell">4</div>
    </div>
    let wrapper = document.querySelector('.wrapper')
    console.log(wrapper.offsetWidth);     // 670
    console.log(wrapper.clientWidth);     // 650
    console.log(wrapper.scrollWidth);     // 650

clientWidth

width(内容宽度) + 左右padding - (如超出父级宽高会出现滚动条,需减去滚动条宽);
width 650px + 左右padding 0px - 滚动条宽 = clientWidth可视宽度 635px


offsetWidth

width(内容宽度) + 左右padding + 左右border宽度; (即使出现滚动条,也已包含滚动条的宽度)

width 650px + 左右padding 0px + 左右border 10px = 670px


scrollWidth:

width(内容宽度) + 左右padding + 不加左右border宽度 + 而是加溢出的宽度;
(也就是整个子元素占据的宽度 + 子元素margin宽度 = 父元素.scrollWidth)

  • 下图是用scrollHeight举例;计算方式同理;
    (子元素cell高度100px + cell的下边距20px ) * 2 = wrapper.scrollHeight 240px


相关文章

网友评论

      本文标题:css offsetWidth,clientWidth,scro

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