获取宽高:
- 使用offsetWidth和offsetHeight属性,获取元素的自身宽高,其中包含元素自身设置的宽高、内边距padding、边框border
- 取出来的是数值
- 获取的是可视宽高。如果盒子是隐藏的,获取的结果是0
获取位置:
- 获取元素距离自己最近的定位祖先元素的左、上距离,使用 offsetLeft 和 offsetTop,这两个是只读属性。
- 受祖先元素的影响,如果直接父级元素有定位,以直接父级元素为准;如果直接父级元素没有定位,一直找最近一级带有定位的祖先元素为准。
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector('div')
console.log(div.offsetLeft)
</script>
</body>
</html>
控制台打印的offsetLeft是108,而不是100,这是因为body有一个8像素的外边距(margin):
父级元素没有定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
p {
width: 100px;
height: 100px;
background-color: purple;
margin: 50px;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
const div = document.querySelector('div')
const p = document.querySelector('p')
// console.log(div.offsetLeft)
console.log(p.offsetLeft)
</script>
</body>
</html>
打印的p的offsetLeft是158,它是p元素50像素的margin+div元素100像素的margin+body元素8像素的margin:
示例:父级元素有定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
p {
width: 100px;
height: 100px;
background-color: purple;
margin: 50px;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
const div = document.querySelector('div')
const p = document.querySelector('p')
// console.log(div.offsetLeft)
console.log(p.offsetLeft)
</script>
</body>
</html>
现在p元素的offsetLeft是50: