美文网首页
JS第七天-01

JS第七天-01

作者: knot98 | 来源:发表于2018-10-19 21:43 被阅读0次

    JS盒模型

    1、width | height

    • parseInt(getComputedStyle(ele, null).getPropertyValue('width'))
    • parseInt(getComputedStyle(ele, null).getPropertyValue('height'))

    2、padding + width | padding + height

    • clientWidth
    • clientHeight

    3、border + padding + width | border + padding + height

    • offsetWidth
    • offsetHeight

    4、结合绝对定位,距离最近定位父级的Top | Left

    • offsetTop
    • offsetLeft

    代码示例:

    <!DOCTYPE html>
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <title>JS盒模型</title>
    
        <style type="text/css">
            .sup {
                width: 200px;
                height: 200px;
                padding: 30px;
                border: 5px solid black;
                background-color: orange;
                margin: 20px;
                position: relative;
            }
    
            .sub {
                width: 100px;
                height: 100px;
                padding: 20px;
                border: 5px solid black;
                background-color: red;
                position: absolute;
                top: 0;
                left: 20px;
            }
        </style>
    </head>
    <body>
        <div class="sup">
            <div class="sub"></div>
        </div>
    </body>
    <script type="text/javascript">
        var sup = document.querySelector('.sup');
        // 盒子content的width
        var width = parseInt(getComputedStyle(sup, null).width);
        console.log(width);
    
        // 盒子padding+width => 子级的可活动范围
        var p_width = sup.clientWidth;
        console.log(p_width);
    
        // 盒子border+padding+width => 可视区域
        var b_p_width = sup.offsetWidth;
        console.log(b_p_width);
    
        // 盒子距离定位父级的top,left
        var sup_top = sup.offsetTop;
        var sup_left = sup.offsetLeft;
        console.log(sup_top);
        console.log(sup_left);
    
    
        var sub = document.querySelector('.sub');
        // 父级定位(relative)后,子级活动区域为父级的client(padding+width)区域
        var sub_top = sub.offsetTop;
        var sub_left = sub.offsetLeft;
        console.log(sub_top);
        console.log(sub_left);
    
    </script>
    </html>
    

    相关文章

      网友评论

          本文标题:JS第七天-01

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