先看下简单的代码吧。<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Untitled Document</title>
<style type="text/css">
#div1{
margin:auto;
width: 300px;
height:300px;
border-style: solid;
border-bottom-width:inherit;
border-color:red;
padding:10px;
overflow:auto;
}
#div2{
width: 600px;
height:600px;
background-color:blue;
}
</style>
<script type="text/javascript">
window.onload=function(){
var div=document.getElementById("div1");
appendPElement("div1");
appendPElement("offsetLeft:"+div.offsetLeft+" offsetTop:"+div.offsetTop); div=document.getElementById("div2");
appendPElement("div2");
appendPElement("offsetLeft:"+div.offsetLeft+" offsetTop:"+div.offsetTop);
}

function appendPElement(text){
var p=document.createElement("p");
p.appendChild(document.createTextNode(text));
document.body.appendChild(p);
}
</script>
</head>
<body>
<div id="div1">
<div id="div2"></div>
</div>
</body>
</html>
在如上代码中,为什么div2的父元素是BODY而不是div1。
如果把上面的div1的css改为#div1{
margin:auto;
width: 300px;
height:300px;

border-style: solid;
border-bottom-width:inherit;
border-color:red;
padding:10px;
overflow:auto;
}
这时div2的父元素就是div1了,请问这是为什么啊,献上30分

解决方案 »

  1.   

    难道是CSS能改变DOM结构? 不是吧....
      

  2.   

    offsetParent 在不同的浏览器中会有不同的表现,
    在FF中,无论对象的position怎么定位,offsetParent指向的都是html标签(反正是个很顶层的标签),
    而IE,除了static定位,其它fixed,absulote和FF一样...IE的static定位,和对象的parentNode指向是同一个,,在ie中,计算一个static定位(默认的定位)对象的offsetLeft的值是很复杂的你要想很好地看这些值,不如下载我发布的那个资源,一清二楚
      

  3.   

    没写错吗?前后两个div1的CSS是一样的。
    offsetParent顾名思义应该是指的能够作为基础定位元素的父元素吧,并不是任何元素都可以。而可以影响子元素定位的元素必须具有position: absolute/relative/fixed;所以position属性是可以改变offsetParent的。
      

  4.   

    嗯,第二份CSS是写错了,应该是这样的:#div1{
    position:absolute;
    left:600px;
    top:100px;
    width: 300px;
    height:300px;
    border-style: solid;
    border-bottom-width:inherit;
    border-color:red;
    padding:10px;
    overflow:auto;
    }
      

  5.   

    所以我3楼的分析没错哦,具有position: absolute/relative/fixed的元素才会实当作offsetParent.