繁体   English   中英

如何找到HTML元素的绝对坐标?

[英]How to find the absolute the coordinates of an html element?

在此处输入图片说明

我需要根据屏幕找到html元素的绝对坐标。 我知道我可以使用getBoundingClientRect()。top和getBoundingClientRect()。left方法来根据视口计算坐标。 如何找到绝对坐标? 另一个问题是window.screenX是否考虑了网址和标签栏? 感谢帮助。

更新

添加了特殊的度量:

var offset = window.outerHeight - window.innerHeight

这是浏览器的顶部,在浏览器栏的底部(或视口的顶部)。 名为UselessXY的新坐标将使用浏览器栏的高度并将其添加到Y坐标。 如果调整了浏览器的大小,则需要刷新浏览器以获得新的偏移量。 如果浏览器已最大化,则效果最佳。

我制作了一个将显示clientXclientYscreenXscreenY offsetuselessXY只需单击任意位置即可获取坐标。

SNIPPET

 <!doctype html> <html> <head> <meta charset="utf-8"> <title>COORDS</title> <style> *, *:before, *:after { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; position: relative; } #display { width: 40ex; height: 50px; border: 1px solid grey; padding: 3px; position: absolute; } </style> </head> <body onmousedown="coords(event)"> <figure id="display" onmouseover="this.style.left = '50%'" onclick="this.style.left = '0'"> <figcaption><u>Coordinates(X,Y)</u></figcaption> <output id="xy"></output> </figure> <script> function coords(evt) { document.getElementById('xy').textContent = "screenXY: " + evt.screenX + ", " + evt.screenY +" | clientXY: " + evt.clientX + ", " + evt.clientY+" | Offset: "+offset+" | UselessXY: "+evt.screenX+", "+(evt.screenY + offset); } var offset = window.outerHeight - window.innerHeight; </script> </body> </html> 

如何找到绝对坐标?

使用offsetTop

假设元素的ID为

var d = document.getElementById("socialChange");
var topPos = d.offsetTop;

另一个问题是window.screenX是否考虑了网址和标签栏?

否,请点击此处查看文档。 浏览器控件所覆盖的区域不包括在window.screenXwindow.screenY

x_axis = window.screenX +(window.outerWidth-window.innerWidth)+ element.getBoundingClientRect()。left

上面的内容将从屏幕左侧获取绝对长度。 y轴也可以做类似的情况。

从概念上来看,可以使用此图片。 在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM