鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ 如何正確計算元素(父級有相對定位)的offset值

如何正確計算元素(父級有相對定位)的offset值

在計算元素的offset的時候,如果其多個父級定位有相對定位,則該元素的offset的值會受相對定位的影響。

clipboard.png
比如想算div.container 的offset,則會有60像素的偏移。

回答
編輯回答
編輯回答
呆萌傻

不會呀,估計你代碼有其他問題

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>

<body>
    <style>
        body{margin:0;padding:0;position:relative;}
        #box{position:relative;width:200px;height:200px;background:#ddd;margin:25px auto;}
        #test{width:100px;height:100px;background:#000;margin:0 auto;}
        .big{position:relative;width:250px;height:250px;background:#dd4215;margin:20px auto;overflow:hidden;}
    </style>
    <div class="big">
        <div id="box">
            <div id="test"></div>
        </div>
    </div>
    <button>點我看offsetTop</button>
    
    <script>
        var oTest = document.getElementById('test');
        var oButton = document.getElementsByTagName('button')[0];
        
        oButton.onclick = function () {
            alert('top:' + oTest.offsetTop + '\r\nleft:' + oTest.offsetLeft)
        };
    </script>
</body>
</html>
2018年8月31日 11:25