js学习笔记之offset

    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            padding: 10px;
            border: 10px solid red;
            margin: 100px;
            background: pink;
        }
        .box1{
            width: 300px;
            height: 300px;
            padding: 120px;
            margin: 100px;
            position: relative;
            background: pink;
        }
        .box2{
            width: 100px;
            height: 100px;
            background: red;

        }
    </style>
<body>
        <!--<div id="box"></div>-->
        <div class="box1">
            <div class="box2" style="position:fixed">
                <div class="box3"></div>
            </div>
        </div>

    </body>
<script type="text/javascript">
    //宽高
    //var box = document.getElementById("box");
    //offsetHeight和offsetWidth可以检测出盒子的高宽,包括高宽本身,padding,border不但包括margin
    //console.log(box.offsetHeight,box.offsetWidth)
    //左上距离
    var box2 = document.getElementsByClassName("box2")[0];
    //console.log(box2.offsetLeft,box2.offsetTop)
    //1.offsetLeft可以返回没有定位盒子的距离左侧的位置,如果父亲盒子没有,则返回据body的距离,style.left只能获取行内式,如果没有返回“”;
    //2.offsetTop返回的是数字。而style.top返回的是字符串,出数字外还带有px;
    //3.offsetTop是只读,而style.top是可读写(只读是获取值,可读写是赋值)offsetLeft/Top只能获取值,style.top/left可赋值
    //4.如果没有HTML元素指定过TOP样式,则style.top返回的是空字符串。


    //带有定位的盒子
    //如果父亲盒子没有定位返回body,如果有返回最近的父亲盒子
    var box3 = document.getElementsByClassName("box3")[0];
    console.log(box3.offsetParent);
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值