js offset系列属性
约 686 字大约 2 分钟
2025-07-30
offsetParent
:返回该元素有定位的父级,如果父级都没有定位则返回 bodyoffsetTop
:返回元素相对父级(带有定位的父级)上方的偏移offsetLeft
:返回元素相对父级(带有定位的父级)左边框的偏移offsetWidth
:返回自身的宽度,包括 padding、border、内容区,返回数值不带单位offsetHeight
:返回自身的高度,包括 padding、border、内容区,返回数值不带单位style.width
只能获取行内样式的数据,返回有单位,能用 js 修改数值offsetWidth
只能读不能改,返回无单位
注意:<style></style>
要放在 js 代码前面,js 中才能正确获取 offset
系列属性。如果 style
代码要放在 js 代码后面,需要使用 window.onload
等待资源加载完毕再执行 js 代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="parent">
<div class="child">child</div>
<div
id="style"
style="width: 88px;height: 66px;background-color: #00FFFF;"
>
test style
</div>
</div>
</body>
<script>
window.onload = function () {
/**
* offsetParent:返回该元素有定位的父级,如果父级都没有定位则返回body
*
* offsetTop:返回元素相对父级(带有定位的父级)上方的偏移
* offsetLeft:返回元素相对父级(带有定位的父级)左边框的偏移
* offsetWidth:返回自身的宽度,包括padding、border、内容区,返回数值不带单位
* offsetHeight:返回自身的高度,包括padding、border、内容区,返回数值不带单位
*
* style.width 只能获取行内样式的数据,返回有单位,能用js修改数值
* offsetWidth只能读不能改,返回无单位
* */
var parent = document.querySelector(".parent");
console.log("parentNode:", parent.parentNode);
var child = document.querySelector(".child");
console.log("offsetParent:", child.offsetParent);
console.log("offsetTop:", child.offsetTop);
console.log("offsetLeft:", child.offsetLeft);
console.log("offsetWidth:", child.offsetWidth);
console.log("offsetHeight:", child.offsetHeight);
console.log("--------------------------------");
var style = document.querySelector("#style");
console.log("offsetWidth:", style.offsetWidth);
console.log("style.width:", style.style.width);
style.style.width = 111 + "px"; //这句生效,注意加单位
console.log(style.style.width);
style.offsetWidth = 222 + "px"; //这句不生效
console.log(style.offsetWidth);
};
</script>
<style>
* {
padding: 0;
margin: 0;
}
.parent {
position: relative;
display: inline-block;
width: 200px;
height: 200px;
margin: 50px;
background-color: #008000;
}
.child {
display: inline-block;
position: absolute;
width: 50px;
height: 50px;
margin: 10px;
border: 5px solid yellow;
background-color: red;
}
#style {
position: absolute;
bottom: 0;
right: 0;
}
</style>
</html>
style
和 offsetWidth
的区别
style.width
只能获取行内样式的数据,返回有单位,能用 js 修改数值offsetWidth
只能读不能改,返回无单位
对于“style.width
只能获取行内样式的数据 ”:如果没有行内样式,第一次获取 style.width
会是空,但是给 style.width
赋值后,再次获取能正常获取到值。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
div {
width: 100px;
height: 100px;
position: absolute;
background-color: #008099;
}
</style>
</head>
<body>
<div></div>
</body>
<script type="text/javascript">
var div = document.querySelector("div");
// div.style.left = 102 + "px";
console.log(div.style.left);
</script>
</html>
div.style.left = 102 + "px";
console.log(div.style.left);