今天通过Javascript求元素的offSetLeft的时候,发现无论子元素的直接父元素是不是body,通过offSetParent取得的都是body元素。比如:
<html>
<body id = "body">
<p id = "p1">
<p id = "p2">
<img id = "img" src="./example.png" alt="example">
</p>
</p>
</body>
</html>
通过document.getElementById("img").offSetParent取得的是body元素,为什么会跳过其它的父级元素(p元素)?

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为外层的p没有进行定位,你需要使用 absolute或relative进行定位。
html in standards compliant mode; body in quirks rendering mode
当没有定位过的父标签,会根据html文档模式返回不同的标签。