hi,欢迎访问本站!
当前位置: 首页Web前端正文

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

墨初 Web前端 702阅读

想要获取一个html元素相对于浏览器的可视窗口的坐标位置,可以使用js中的 getBoundingClientRect 方法,此方法返回一个参数的集合对象,包括元素相对于浏览器可视窗口的 top,left以及right等属性。

JS getBoundingClientRect 方法

getBoundingClientRect:返回指定元素相对于浏览器可视窗口的坐标。

PS:

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

jQuery 获取元素相对于窗口的位置,javascript js jquery获取元素位置代码,js获取元素相对窗口位置的实现代码

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

js脚本示例代码,将下面的代码复制到本地,保存为html文件即可!

<!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">73so.com</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脚本代码也是直接可以调用js脚本中的方法的,下面是jq使用 getBoundingClientRect 方法案例!

<!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">73so.com</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>
声明:无特别说明,转载请标明本文来源!
相关推荐