JavaScript中的offsetLeft以及obj.style.left

1, offsetLeft 获取的是相对于父对象的左边距;
2, left 获取或设置相对于具有定位属性(position定义为relative)的父对象 的左边距;
下面看看一些例子

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #div1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="div1"></div>
    <script type="text/javascript">
        function getStyle(obj, attr) {
            if (obj.currentStyle) {//IE
                return obj.currentStyle[attr];
            } else {
                return getComputedStyle(obj, null)[attr];
            }
        }
        var oDiv = document.getElementById('div1');
        console.log('getStyle("left") = ' + getStyle(oDiv, 'left'));
        console.log('offsetLeft = ' + oDiv.offsetLeft);
    </script>
</body>
</html>

结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0


#div1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    border: 3px solid black;
}

结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0


#div1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    border: 3px solid black;
    padding: 14px;
}

结果:oDiv.style.left = 0px , oDiv.offsetLeft = 0


#div1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    border: 3px solid black;
    padding: 14px;
    margin-left: 24px;
}

结果:oDiv.style.left = 0px , oDiv.offsetLeft = 24


可见,offsetLeft是考虑到了margin-left了,因为margin-left,div确实在左边空出了24px的空间,但是style.left不管,style.left只看样式表中的left,其他的不管,就像前文中讲到的offsetWidth, offsetWidth不仅仅考虑到样式表中的width,更是考虑到padding和border,如下:

offsetWidth = width + padding + border;


#div1 {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    border: 3px solid black;
    padding: 14px;
    margin-left: 24px;
}

结果:oDiv.style.width = 100px , oDiv.offsetWidth = 134 (100+3+3+14+14)


可见style.left得到的是字符串,带单位,而offsetLeft得到的是数字;
写在CSS样式里的width等样式你直接用style.width是获取不到的,但是用offsetWidth可以;
style.left可读可写,但是offsetLeft可读不可写;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值