javascript - DOM 对象的 jQuery xy 文档坐标

标签 javascript jquery user-interface location

我需要获取 DOM 元素的 X、Y 坐标(相对于文档的顶部/左侧)。我找不到任何可以给我这些的插件或 jQuery 属性或方法。我可以获得 DOM 元素的顶部和左侧,但这可以是相对于其当前容器/父级或文档的。

最佳答案

你可以使用Dimensions插件 [弃用...包含在 jQuery 1.3.2+ 中]

offset()
Get the current offset of the first matched element, in pixels, relative to the document.

position()
Gets the top and left position of an element relative to its offset parent.

知道了这一点,就很容易了...(使用我的小 svg project 作为 example page )

var x = $("#wrapper2").offset().left;
var y = $("#wrapper2").offset().top;

console.log('x: ' + x + ' y: ' + y);

输出:

x: 53 y: 177

希望对您有所帮助。

这是 offset() 和 position() 的图像

使用 XRay

alt text

使用 Web Developer工具栏

alt text

关于javascript - DOM 对象的 jQuery xy 文档坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1002934/

相关文章:

javascript - Async Await 可以在没有 promise 的情况下工作吗? (简单的例子)

javascript - 使用 JavaScript 提交

jquery - 删除字符串中的所有 HTML 标签(使用 jquery text() 函数)

c# - Css display none 不适用于 div 及其内容

user-interface - 是否存在像 Code Bubbles 这样的东西?

android - 使用productFlavors时不能继承自定义主题

qt - 在 Qt 中旋转图像

javascript - 在 javascript var 中检索 mysql 数据

javascript - 可丢弃事件偶尔不起作用

javascript - 函数调用中的语法错误