css offsetWidth,clientWidth,scro

2022-12-08  本文已影响0人  Peter_2B
    <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)

上一篇 下一篇

猜你喜欢

热点阅读