javascript - 如何获取计算机屏幕上元素的像素坐标

标签 javascript jquery html

我想知道 html 元素在屏幕上的左侧和顶部位置。 我尝试使用这段代码来获取文档中元素的位置:

var position = $('#elem').position();

但是我想知道是否有一个函数可以找到屏幕上的位置,或者是否有办法知道该点在屏幕上的坐标:enter image description here

提前谢谢您!

最佳答案

您可能正在寻找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/

相关文章:

javascript - Bootstrap Alert 的干净示例

javascript - Web 应用程序和桌面应用程序之间的细线

JavaScript 不适用于动态内容

javascript - 无论是否附加了 Chrome 调试器,日期构造函数的工作方式都不同

javascript - 哇 slider 和 fancybox(灯箱)不能一起工作

javascript - asp.net mvc 4在bootstrap模式插件中注册

html - 如何仅在div的顶部和底部添加渐变边框

javascript - 是否可以模拟 'window.confirm()'这样的阻塞对话框?

javascript - Margin-top 和 Margin-bottom 不适用于内部元素

javascript - 如何在 javascript 中将参数传递到循环之外