获取元素位置的几种方法:
1.clientWidth 和 clientHeight 是元素的宽度与高度 + padding ,也可以看做是元素内部的宽度与高度。
2. offsetWidth 和 offsetHeight 是元素的宽度与高度 + padding + border ,也可以看做是元素的外边界宽度。
3. clientLeft 和 clientTop 获取的是元素的内容边界 到外边界的宽度与高度 其实就是边框的宽度。
.box{
width: 200px;
height: 200px;
background-color: #DB7093;
padding: 10px;
border: 10px solid red;
position: absolute;
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
var box=document.querySelector('.box');
// 元素的宽度与高度
console.log(box.clientHeight,box.clientWidth); //220 220
console.log(box.offsetHeight,box.offsetWidth) //240 240
// 元素的位置
console.log(box.clientLeft,box.clientTop) //10 10
console.log(box.offsetLeft,box.offsetTop) //100 100
</script>
4.offsetLeft 和 offsetTop 获取的就是元素的偏移。
offsetLeft 和 offsetTop 的参照物是开启了定位的父元素,如果父元素没有开启定位,就一级一级的往上找,直到找到body为止。
5.有些情况下我们不方便使用offsetLeft和offsetTop去获取元素相对于视口的位置 比如说结构非常复杂或祖先元素开启过定位,这时我们就需要使用另一个方法,我们称作获取元素相对于视口的位置最干净的获取方式。这个方法不会受到任何的嵌套关系和样式的影响,就是返回元素相对于视口的位置。该方法返回值为一个对象,内部包含八个属性: width height x y left top right bottom。
获取到的位置都是相对于视口的左侧与顶部的。
left值 返回的值 元素的左边界到视口的左边界的距离。
right 返回的值 元素的右边界到视口左边界的距离。
.box{
width: 400px;
height: 400px;
background-color: #00FFFF;
margin-left: 50px;
position: absolute;
left: 50px;
top: 50px;
}
.box2{
width: 300px;
height: 300px;
background-color: #DB7093;
margin-left: 50px;
position: absolute;
left: 40px;
top: 40px;
}
</style>
</head>
<body>
<div class="box">
<div class="box2"></div>
</div>
<script type="text/javascript">
var box=document.querySelector('.box');
var box2=document.querySelector('.box2');
console.log(box.offsetLeft,box.offsetTop); //100 50
console.log(box2.offsetLeft,box2.offsetTop); //90 40
console.log(box.getBoundingClientRect().left); //100
console.log(box.getBoundingClientRect().top); //50
console.log(box2.getBoundingClientRect().top); //90
</script>