先看下简单的代码吧。<!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分
<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分
在FF中,无论对象的position怎么定位,offsetParent指向的都是html标签(反正是个很顶层的标签),
而IE,除了static定位,其它fixed,absulote和FF一样...IE的static定位,和对象的parentNode指向是同一个,,在ie中,计算一个static定位(默认的定位)对象的offsetLeft的值是很复杂的你要想很好地看这些值,不如下载我发布的那个资源,一清二楚
offsetParent顾名思义应该是指的能够作为基础定位元素的父元素吧,并不是任何元素都可以。而可以影响子元素定位的元素必须具有position: absolute/relative/fixed;所以position属性是可以改变offsetParent的。
position:absolute;
left:600px;
top:100px;
width: 300px;
height:300px;
border-style: solid;
border-bottom-width:inherit;
border-color:red;
padding:10px;
overflow:auto;
}