<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div1{ 200px; height: 200px; background: #ccc; margin: 100px; position: relative; } #div2{ 100px; height: 100px; background: red; position: absolute; left: 50px; top: 50px; } </style> <script> //父级有定位的时候 offsetParent 获取的就是父节点 //父级没有定位的时候 获取的就是body window.onload = function(){ var oDiv2 = document.getElementById("div2"); alert(oDiv2.offsetParent); } </script> </head> <body> <div id="div1"> <div id="div2"></div> </div> </body> </html>
和parentNode