18910140161

jquery获取元素的坐标 js/jq获取元素相当于窗口(视窗)坐标位置的方法

顺晟科技

2022-10-21 13:06:09

169

项目中遇到个需要利用JS脚本获取元素相当于窗口(浏览器的显示区域并不是文档)坐标位置的需求,试了很多的方法,发现都不是很精确,不是相对于父元素就是相对于整个DOM文档的坐标位置。后来百度到一个DOM的 getBoundingClientRect 方法,可以获取指定元素相对于窗口的坐标位置,实现方法如下。

JS getBoundingClientRect 方法

js中的 getBoundingClientRect 方法可以获取到某个html元素相对于视窗(浏览器窗口)的位置集合,并返回一个对象.

注意:

getBoundingClientRect 会获取元素的相对于浏览器窗口的 top , left , right , bottom ,width,height 的属性,这些属性会以一个对象的方法返回。

getBoundingClientRect 获取的数据参考下图:

js/jq获取元素相当于窗口(视窗)坐标位置的方法

js 获取元素相对于窗口坐标的方法

js示例代码:

<!DOCTYPE html>
<html>
<head>
    <style>
        #mochu{
            margin-top: 100px;
            margin-left: 200px;
            width: 100px;
            height: 100px;
            background-color: red;
            color: #fff;
        }
    </style>
</head>
<body>
    <div id="mochu">顺晟科技博客</div>
    <script>
        var xy = document.getElementById('mochu').getBoundingClientRect();
        console.log(xy.x); // 208
        console.log(xy.y); // 100
        console.log(xy.left); //208
        console.log(xy.top); //100
        console.log(xy.right); // 308
        console.log(xy.bottom); // 200
        console.log(xy.width); // 100
        console.log(xy.height); // 100
    </script>
</body>
</html>
jq 获取元素相对于窗口坐标的方法

在jq代码中也可以直接调用 getBoundingClientRect 方法,其使用方法也非常的简单!

jq代码示例:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <style>
        #mochu{
            margin-top: 100px;
            margin-left: 200px;
            width: 100px;
            height: 100px;
            background-color: red;
            color: #fff;
        }
    </style>
</head>
<body>
    <div id="mochu">顺晟科技博客</div>
    <script>
        var xy = $('#mochu')[0].getBoundingClientRect(); //注意这里的调用方法与JS不相同
        console.log(xy.x); // 208
        console.log(xy.y); // 100
        console.log(xy.left); //208
        console.log(xy.top); //100
        console.log(xy.right); // 308
        console.log(xy.bottom); // 200
        console.log(xy.width); // 100
        console.log(xy.height); // 100
    </script>
</body>
</html>
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航