Javascript 绝对定位和相对定位

时间:2022-01-03 12:43:26
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
#div1
{
width:400px;height:400px;background-color:red;position:relative;margin:100px;
}
#div2
{
width:100px;height:100px;background-color:gray;position:absolute;left:200px;top:200px;
}
</style>
<script type="text/javascript">
window.onload = function () {
var oDiv1 = document.getElementById("div1");
var oDiv2 = document.getElementById("div2");
alert(oDiv2.offsetParent);
//如果div1有相对定位,则,div2根据div1定位,如果div1,没有相对定位,则div2根据body相对定位。可以去掉相对定位,看一下alert出来的内容的区别 }
</script>
</head>
<body>
<div>子类的position:absoulte;父类元素只有相对定位后,移动位置,子类才能跟着移动</div>
<div id="div1">
<div id="div2"></div>
</div>
<!--//总结一下Dom节点
childNodes nodeType 元素节点的 nodeType=1 文本节点的 nodeType=3 使用的时候是 对象.childNodes[i].style.background='red';
children 都是元素节点 children[i].style.background='red' parentNode parentNode.style.background="red" offsetPraent 获取元素在页面上的实际位置 <有兼容性问题>子节点
firstChild firstElementChild
lastChild lastElemetnChild
<有兼容性问题>兄弟节点
nextSiblings nextElementSiblings
previousSiblings previousElementSiblings
-->
</body>
</html>