JS offset属性及与style、client系列属性的区别

148 阅读1分钟
    offset对象用于获取元素的位置,属性以带有定位的父元素为准
    <div class="father">
        <div class="son"></div>
    </div>
    let father = document.querySelector('.father')
    let son = document.querySelector('.son')
    //offset属性以带有定位的父元素为准
    //1.元素的定位element.offsetTop offsetLeft 只能获得元素顶部与左方的距离 距离最近有定位的父元素

    console.log( father.offsetTop );
    console.log( father.offsetLeft );   //father没有定位的父元素  因此距离是相对body

    console.log( son.offsetTop )
    console.log( son.offsetLeft )   //在这里father有定位 是son的父元素 所以距离相对father

    //2.获得元素的宽高 element.offsetWidth element.offsetHeight
    // 宽是 width+border+padding相加而来的  高也一样

    console.log( father.offsetWidth )
    console.log( father.offsetHeight )

    //3.element.offsetParent  查找有定位的父元素
    console.log( father.offsetParent )  //body
    console.log( son.offsetParent )     //father

与style的区别


    1.offset可以获得任意样式的值 style只能获取行内样式的值
    2.offset返回数值无单位 style有单位
    3.offset只读属性 style可读可写
    

与client系列属性区别

    client系列属性与offset属性不同点在于 client不包含边框 其余相同
    //<div></div>

    let div = document.querySelector('div')

    //client系列属性与offset属性不同点在于 client不包含边框 其余相同
    //clientWidth 不包括边框
    console.log( div.clientWidth )
    //clientHeight
    console.log( div.clientHeight )
    //clientTop
    console.log( div.clientTop ) //上边框宽度

    console.log( div.clientLeft ) //左边框宽度

    //offsetWidth
    console.log( div.offsetWidth )