获取Dom元素与浏览器窗口的位置(二)----- getBoundingClientRect()方法
getBoundingClientRect()
这个方法可以在不需要额外传参的情况下获取Dom
元素的位置,但是值得注意的是,他获取到的位置是可视区范围的,不包括文档滚动的距离
下面我们用一张图来表示他获取到的Dom
元素相关信息
上面的那张图让我们对getBoundingClientRect
有了一个整体的初步认识,为了更加直观和细致的感受getBoundingClientRect
的用法,下面我打算用一个简单的案列来总结这个方法的正确使用姿势:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>getBoundingClientRect</title>
<style>
.record{
width: 200px;
min-height: 200px;
background-color: #e99e83;
text-align: center;
margin: 30px 20px;
}
body {
margin: 0;
}
</style>
</head>
<body>
<div class="record"></div>
</body>
<script>
const dom = document.querySelectorAll('.record')[0]
console.log(dom)
const domObj = dom.getBoundingClientRect()
console.log(domObj)
</script>
</html>
上面代码得到的UI
和控制台打印如下:
我们通过查阅Can I Use
可以知道,虽然getBoundingClientRect
兼容性还可以,但是在IE
上还是有所区别的,因此,为了后续使用方便,我们自己可以基于getBoundingClientRect
封装一个自己的兼容IE
的获取dom
元素位置的方法
function GetDomPosition(dom) {
const { top, bottom, left, right, height, width } = dom.getBoundingClientRect()
return {
top, // '元素顶部相对于视口顶部的距离',
bottom, // '元素低部相对于视口顶部的距离',
left, // '元素左边相对于视口左边的距离',
right, // '元素右边相对于视口左边的距离',
height: bottom - top || height, // 元素高度
width: right - left || width // 元素宽度
}
}
叮叮叮!!!-------------当然获取元素坐标位置宽高等信息的方法有很多,除了这篇之外,之前还写过一篇获取元素宽高和距离定位父级的距离,有兴趣的欢迎交流哦