我想知道 html 元素在屏幕上的左侧和顶部位置。 我尝试使用这段代码来获取文档中元素的位置:
var position = $('#elem').position();
但是我想知道是否有一个函数可以找到屏幕上的位置,或者是否有办法知道该点在屏幕上的坐标:
提前谢谢您!
最佳答案
您可能正在寻找Element.getBoundingClientRect() .
The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box in pixels. top and left are relative to the top-left of the viewport.
例如,这是非滚动页面上问题元素的结果:
document.querySelector("#question").getBoundingClientRect()
{
"height": 633,
"width": 728,
"left": 431.5,
"bottom": 844,
"right": 1159.5,
"top": 211
}
还有一点滚动:
{
"height": 633,
"width": 728,
"left": 431.5,
"bottom": 10,
"right": 1159.5,
"top": -623
}
关于javascript - 如何获取计算机屏幕上元素的像素坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26274512/