JS18-获取元素占位

在这里插入图片描述

<style>
    *{
        margin: 0;
        padding: 0;
    }

    div{
        width: 100px;
        height: 10px;
        margin: 20px;
        padding: 40px;
        border:1px solid black;
        /* box-sizing: border-box; */
    }
</style>
</head>
<body>
<div></div>

<script>
    // DOM操作之获取元素占位

    // 1,获取元素占位 --- css样式占位,盒子模型
    // 宽度,高度,margin,padding,border
    // 可以通过标签样式,来获取
    // 获取到的结果,是属性值,有px单位
    // 去除px单位的方法 ? 

    var oDiv = document.querySelector('div');
    console.log(window.getComputedStyle(oDiv).width);
    console.log(window.getComputedStyle(oDiv).height);

    // 2,其他方式
    // offsetHeight   offsetWidth
    // 高/宽 + padding + border

    // clientHeight   clientWidth
    // 高/宽 + padding

    // clientLeft   clientTop
    // 左/上 border

    // offsetLeft   offsetTop
    // 左/上 margin


    // 如果设定了  box-sizing: border-box;
    // 边框线,margin的数据是不受影响的

    // clientHeight   clientWidth 
    // 高/宽 + padding --->  width/height - border
    // 实际就是 定义 width/height - border


    // offsetHeight   offsetWidth
    // 高/宽 + padding + border ---> width / height
    // 实际就是 定义的 width / height 数值
        
    console.dir(oDiv)

    // 边框线和外边距不能设定,要通过style来设定

    // 也是不能设定的
    oDiv.offsetHeight = '300px';
    oDiv.clientHeight = '300px';

    // 不能设定
    oDiv.clientLeft = '100px';
    oDiv.offsetLeft = '100px';

    // style可以设定  boder 和 margin
    oDiv.style.borderLeft = '100px solid red';
    oDiv.style.marginLeft = '100px';

    // 如果非要设定,之后有方法解决
</script>
发布了103 篇原创文章 · 获赞 4 · 访问量 2003

猜你喜欢

转载自blog.csdn.net/DcTbnk/article/details/105268720