天天看点

offsetLeft,offsetTop,offsetWidth,offsetHeight的使用

元素.offsetLeft[Top]:只读属性,当前元素到定位父级的距离(偏移值),也可以理解成到当前元素的offsetParent的距离。

1.如果当前元素和父级都没有定位情况:‘

例一:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <style>
        *{margin:;padding:;}
        div {padding: px px;}
        #div1 {background: red;}
        #div2 {background: green; }
        #div3 {background: orange; }
    </style>
    <script>
        window.onload = function() {

            var oDiv3 = document.getElementById('div3');

             alert( "距离上面的距离是:"+oDiv3.offsetTop+"距离左边的距离是:"+oDiv3.offsetLeft );

        }
    </script>
</head>
<body id="body1">
<div id="div1">
    <div id="div2">
        <div id="div3"></div>
    </div>
</div>
</body>
</html>
           

结果都是:在各浏览器下结果相同(都是当前元素到body的距离):

offsetLeft,offsetTop,offsetWidth,offsetHeight的使用

2.当前元素没有定位,而父级有定位的情况:

例二:给div2添加定位

在标准的浏览器下,offsetLeft和offsetTop都是到定位父级的距离。

在IE7以下,offsetLeft和offsetTop仍然是到body的距离。

3.当前元素有定位,父级没有定位情况:

例三:

#div2 {background: green; }
#div3 {background: orange; position:relative;}
           

结果都是到body的距离。

4.当前元素和父级都有定位的情况:

例四:

#div2 {background: green; position:relative;}
 #div3 {background: orange; position:relative;}
           

结果都是到定位父级的距离。

综合以上四种情况,注意在非标准IE下的使用。

offsetWidth和offsetHeight:

这里拿style.width,clientWidth进行对比

例五:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <script>
        window.onload = function() {
alert("样式宽为:"+oDiv.style.width+"可视区宽为:"+oDiv.clientWidth+"占位宽为:"+oDiv.offsetWidth);
        }
    </script>
</head>

<body>
<div id="div1" style="width: 100px; height: 100px; border: 1px solid red; padding: 10px; margin: 10px;"></div>
</body>
</html>
           

在各个浏览器下运行结果一样:

offsetLeft,offsetTop,offsetWidth,offsetHeight的使用

根据以上例子可以得出

style.width,clientWidth和offsetWidth的区别:

style.width:样式宽,就是样式里面定义的宽度

cilentWidth:可视区宽=样式宽+padding(可视区宽可以这样理解:当一个容器里面的内容超出容器本身,出现滚动条的时候,在容器内显示的宽度)

offsetLeft,offsetTop,offsetWidth,offsetHeight的使用

offsetWidth:占位宽=样式宽+padding+border=可视区宽+边框

offsetHeight和offsetWidth一样。

继续阅读