只读属性
,返回当前元素与父辈元素之间的距离(不包括边框)。其中父辈元素的取法是有门道的:css
(1).若父辈元素中有定位
的元素,那么就返回距离当前元素最近的定位元素的距离。jquery
(2).若父辈元素中没有定位元素,那么就返回相对于body
的距离。工具
(3).若当前元素具备固定定位(position:fixed;),那么返回的是当前元素与可视窗口
的距离。spa
<div id="a" style="width:400px;height:400px;margin:100px auto 0;background-color: red;">
<div id="b" style="position:relative;width:200px;height:200px;margin:100px auto 0;background-color: blue;">
<div id="c" style="position: fixed;width:50px;height:50px;top:200px;left: 200px;background-color: green;"></div>
<div id="d" style="position: absolute;top:50px;left: 50px;height:100px;width:100px;background-color: yellow">
<div id="e" style="width:50px;height:50px;margin:25px auto 0;background-color: darkred;"></div>
</div>
</div>
</div>
<script>
var a=document.getElementById("a");
var b=document.getElementById("b");
var c=document.getElementById("c");
var d=document.getElementById("d");
var e=document.getElementById("e");
console.log("e:"+ e.offsetLeft, e.offsetTop);// e: 25,25。以具备绝对定位的父辈元素d为参照
console.log("d:"+ d.offsetLeft, d.offsetTop);// d: 50,50。以其相对定位的父元素b为参照
console.log("c:"+ c.offsetLeft, c.offsetTop);// c: 200,200。以可视窗口为参照
console.log("b:"+ b.offsetLeft, b.offsetTop);// b: 612,100。以body为参照
console.log("a:"+ a.offsetLeft, a.offsetTop);// a: 512,100。以body为参照
</script>
复制代码
offsetHeight、offsetWidth返回的是数值
;style.height、style.width返回的是字符串
,单位是“px”code
offsetHeight、offsetWidth只读
;style.height、style.width可读写
ip
offsetHeight、offsetWidth包括元素的边框
、内边距
;offsetWidth=leftborder+leftpadding+width+rightpadding+rightborder;文档
style.height、style.width只包括元素height、width字符串
若是没有为元素设置高度,offsetHeight会根据内容获取高度值
,style.height会返回undefind
get
jquery中使用$(obj).height()
、$(obj).css('height')
来获取元素的高度,返回的是一个带有单位的字符串it
<div id="a" style="width:50px;height:50px;border:5px solid red;padding:10px;margin:50px;background: black;"></div>
<script>
var a=document.getElementById("a");
console.log(a.offsetHeight, a.offsetWidth);//80,80
console.log(a.style.height, a.style.width);//50px,50px
</script>
复制代码
只读属性
,返回当前节点的可视宽度
和可视高度
(不包括边框、外边距)(包括内边距)clientHeight = topPadding + bottomPadding+ height - scrollbar.height
。
<div id="a" style="width:100px;height:50px;border:25px solid blue;background-color:red;overflow: auto;">
hello world!<br> hello world!<br> hello world!<br> hello world!<br> hello world!<br> hello world!<br> hello world!<br> hello world!<br> hello world!<br>
</div>
<script>
var a=document.getElementById("a");
console.log("a:"+ a.clientWidth, a.clientHeight);// a: 83,50。不包括边框和滚动条(17px)
</script>
复制代码
只读属性
,返回当前节点的实际宽度
和实际高度
(不包括边框),没有滚动条时和clientWidth和clientHeight同样
上例中:
console.log("a:"+ a.scrollWidth, a.scrollHeight);// a: 83,324。不包括边框和滚动条的宽度,返回实际高度和宽度
复制代码
可读写属性
scrollTop:返回网页滚动条垂直方向
滚去的距离; scrollLeft:返回网页滚动条水平方向
滚去的距离;
只读属性
,返回窗口文档显示区的高度和宽度,不包括菜单栏、工具栏和滚动条的宽高。 IE不支持这些属性。它用document.documentElement
或 document.body
(与 IE 的版本相关)的 clientWidth
和 clientHeight
属性做为替代。
outerHeight属性设置
或返回
一个窗口的高度
,包括全部界面元素(如工具栏/滚动条)。 outerWidth属性设置
或返回
窗口的宽度
,包括全部的界面元素(如工具栏/滚动)。