offsetLeft和offsetTop的定位机制

offsetLeft和offsetTop
表示相对于最近的祖先定位元素(CSS position 属性被设置为 relativeabsolute 或 fixed 的元素)的左右偏移值

下面的例子中,初次进页面,点击第一个按钮,返回的偏移距离时相对于html文档左上角的偏移值;

第二个按钮则是相对于div,因为将他的父元素div的position属性设为了relative

第三个和第四个则都是相对于body定位

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

    </style>
    <script>
        window.onload = function () {

        };
    </script>
</head>
<body>
<div id="div1">
    <input id="btn1" type="button" value="父元素为默认定位的时候"/>
    <br/>
    <input id="btn2" type="button" value="应用父元素为relative"/>
    <br/>
    <input id="btn3" type="button" value="自己定位为relative"/>
    <br/>
    <input id="btn4" type="button" value="自己定位为absolute"/>

</div>
<script>
    var oBtn1 = document.getElementById('btn1');
    oBtn1.onclick = function () {
        alert(this.offsetParent.tagName);
        alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
    };
    var oBtn2 = document.getElementById('btn2');
    oBtn2.onclick = function () {
        document.getElementById('div1').style.position = 'relative';
        this.value = "应用成功";
        alert(this.offsetParent.tagName);
        alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
    };
    var oBtn3 = document.getElementById('btn3');
    oBtn3.onclick = function () {
        this.style.position = "relative";
        this.style.left = 20+'px';
        this.style.top = 20+'px';
        alert(this.offsetParent.tagName);
        alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
    };
    var oBtn4 = document.getElementById('btn4');
    oBtn4.onclick = function () {
        this.style.position = "absolute";
        this.style.left = 20+'px';
        this.style.top = 20+'px';
        alert(this.offsetParent.tagName);
        alert('offsetLeft:'+this.offsetLeft+'offsetTop:'+this.offsetTop);
    };
</script>

</body>
</html>

offsetParent元素只可能是下面这几种情况:

  • <body>
  • position不是static的元素
  • <table><th> 或<td>,但必须要position: static

在这个例子中,页面是没有任何定位元素,于是,点击按钮后返回的就是body标签了。

body元素为定位元素的终极boss,所以其上头就没有其他定位元素了。也就是说body元素没有offsetParent(尽管有时候html进入offsetParent链)。

另外,在IE和Opera浏览器下,position: fixed的元素没有offsetParent

原文地址:https://www.cnblogs.com/zhuni/p/4708341.html