1、元素偏移量
1.1、offset概述
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9c82a2a0e6e1743d48dce6c49d9a44ec.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.father {
position: relative;
width: 200px;
height: 200px;
background-color: blue;
margin: 150px;
}
.son {
width: 50px;
height: 50px;
background-color: pink;
margin-left: 45px;
}
.w {
width: 200px;
height: 200px;
background-color: skyblue;
margin: 0 auto 200px;
border: 15px solid red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<div class="w"></div>
<script>
var father = document.querySelector('.father');
var son = document.querySelector('.son');
console.log(father.offsetTop);
console.log(father.offsetLeft);
console.log(son.offsetLeft);
var w = document.querySelector('.w');
console.log(w.offsetWidth);
console.log(w.offsetHeight);
console.log(son.offsetParent);
console.log(son.parentNode);
</script>
</body>
</html>
1.2、offset与style的区别
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a3b15ffa6abe9e45dd27af2b8b87aeb8.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="box" style="width: 200px"></div>
<script>
var box = document.querySelector('.box');
console.log(box.offsetWidth);
console.log(box.style.width);
box.style.width = '300px';
</script>
</body>
</html>
1.3、鼠标移动事件
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/25129893ae7f55a292b9d8ace9aaf446.png)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color:pink;
margin: 50px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box = document.querySelector('.box');
box.addEventListener('click',function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
this.innerHTML = 'x坐标是'+x+'y坐标是'+y;
})
</script>
</body>
</html>