JS第七天-01

2018-10-19  本文已影响0人  knot98

JS盒模型

1、width | height

2、padding + width | padding + height

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

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

代码示例:

<!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>
上一篇 下一篇

猜你喜欢

热点阅读