一、offsetWidth和offsetHeight
- 作用: 只能获取对象的宽度和高度,不能修改。
- offsetWifth ( 或offsetHeight) = width (或 height)+border+padding (注意:不包括外边距!)
#box{
width: 555px;
height: 666px;
padding: 11px;
margin: 11px;
border: 2px solid red;
}
console.log(box.offsetWidth,box.offsetHeight);
显示结果:(内容+内边距+边框)
-
与
div.style.width
的区别:①
div.style.width
只获取样式写在行内时的宽度,不包含boder和padding,且能对width进行修改。
console.log(box.offsetWidth,box.offsetHeight);
console.log(box.style.width,box.style.width);
显示结果(box.style.width显示为空):
- 正确形式:
<div id="box" style="width: 100px;height:200px;"></div>
console.log(box.offsetWidth,box.offsetHeight);
console.log(box.style.width,box.style.width);
显示结果:
② 改变box.style.width
(能起作用):
console.log(box.offsetWidth,box.offsetHeight);
box.style.width= 88 + "px";
console.log(box.style.width);
③ 改变box.offsetWidth
(不起作用):
box.offsetWidth = 88 +"px";
console.log(box.offsetWidth);
二、offsetTop和offsetLeft
-
作用: 获取距离有定位的第一个父盒子的左边和上边的距离,若无有定位的父盒子,则相对body而言(注意:不包含border的值,从当前元素外边框算起到父盒子内边框的距离)。
-
执行情况:
- 父盒子有定位情况:
#father{
width: 400px;
height: 300px;
background-color: black;
position:relative;
}
#son{
width: 200px;
height: 150px;
background-color: red;
margin-left: 50px;
padding: 10px;
border:2px solid white;
}
console.log(son.offsetTop,son.offsetLeft)
- 父盒子无定位情况(以body为准):
#father{
width: 400px;
height: 300px;
background-color: black;
/*position:relative;*/
}
console.log(son.offsetTop,son.offsetLeft)
三、offsetParent
- 作用:返回与当前对象最近的带有定位(absolute和relative均可)的父盒子,若父盒子均无定位,则以body为准。
- 执行效果:
- 均无定位:
<div id="grandfather">
<div id="father">
<div id="son"></div>
</div>
</div>
console.log(son.offsetParent);
- 均有定位
<div id="grandfather" style="position:relative;">
<div id="father" style="position: absolute;">
<div id="son"></div>
<div>
</div>
- father无定位,grandfather有定位
<div id="grandfather" style="position:relative;">
<div id="father" >
<div id="son"></div>
</div>
</div>
四、offsetxxx与style.xxx的区别:
- offsetxxx 可以获取到所有的,而style.xxx只能获取到行内的。
- offsetxxx 只能读,不能修改,而style.xxx即可读,又可写。
- offsetxxx 可以返回没有定位的盒子的位置,而style.xxx只能获取到有定位的盒子的位置。
- offsetxxx 返回的是数字,而style.xxx返回的是字符串。
- 如果没有给定当前元素的xxx(以top值为例),style.top返回的是空字符串。
五、client系列
- clienWidth和clientHeight
- clientWidth( 或 clientHeight) = width(或height) + padding(注意:不包括border),即:
offsetWidth=clientWidth+border
offsetHeight=clientHeight+border
- clientTop和clientLeft
clientTop:上边框的宽度
clientLeft:左边框的宽度
六、scroll系列
- scrollWidth和scrollHeight
1.如果盒子的内容没有溢出,与clientWidth、clientHeight一致。
2.如果容器中的内容有溢出,scrollWidth=真实内容的宽度(包括溢出的部分)+左padding,scrollHeight=真实内容的高度(包括溢出的部分)+上padding。
- scrollTop和scrollLeft
- scrollLeft、scrollTop是当前元素的显示(可见)的内容与该元素实际的内容的距离。
- 解释:以scrollLeft为例:
当页面内容太大时,将会出现滚动条。最初看到了页面最左边的内容,这时scrollLeft=0,而不显示超出浏览器可见范围的内容;向右滚动滚动条,scrollLeft的值不断增大,右边原先看不见的内容逐渐显示,左边的内容逐渐隐藏,此时的scrollLeft为当前最左边与实际内容的最左边的距离(即当前从scrollLeft的位置开始显示)。scrollTop类似,只是由水平变成垂直而已。