<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script type="text/javascript" src="off.js"></script>
<style>
*{
margin:0;
padding:0;
}
#son{
width:100px;
height:100px;
background-color:red;
}
#father{
width:200px;
height:200px;
background-color: orange;
margin:100px auto;
position:relative;
padding:3px;
}
#grandfather{
width:300px;
height:300px;
background-color: green;
margin:100px auto;
position:relative;
}
#son2{
height:60px;
background-color: pink;
}
</style>
<script>
window.onload=function()
{
var son=document.getElementById("son");
console.log(son.offsetWidth); //得到自己的宽度和高度,offsetWidth=border+padding+width;
console.log(son.offsetHeight);
var son2=document.getElementById("son2");
var father=document.getElementById("father");
console.log(son.offsetLeft); //返回距离上级(带有定位)的盒子的左边位置的宽度,如果没有定位,以body为主
console.log(son.offsetLeft); //父级,不单单指父亲,父亲没有定位,爷爷有定位,就以爷爷为准
console.log(son.offsetLeft); //offsetLeft从父级的padding开始算,border不算,就是子盒子到定位的父盒子边框到边框的距离
console.log(son.offsetParent.id);//offsetParent返回父级,不一定是爸爸,父级最近的定位元素,如果父级都没有定位,就是body
console.log(son2.style.width); //返回60px,style.width返回的是字符串,还带单位,offsetWidth返回是数字,style.width只能得到行内样式
son2.style.height="100px";//style.height可以读写,更改height值,offsetHeight只能读,得到当前对象的height值
}
</script>
</head>
<body>
<div id="grandfather">
<div id="father">
<div id="son"></div>
<div id="son2" style="width:60px;"></div>
</div>
</div>
</body>
</html>