DMC*_*MCS 49 javascript jquery user-interface location
我需要获取DOM元素的X,Y坐标(相对于文档的顶部/左侧).我找不到任何可以提供给我的插件或jQuery属性或方法.我可以获取DOM元素的顶部和左侧,但这可以相对于其当前容器/父级或文档.
bal*_*dre 92
你可以使用Dimensions插件 [已弃用...包含在jQuery 1.3.2+中]
offset()
获取第一个匹配元素相对于文档的当前偏移量(以像素为单位).position()
获取元素相对于其偏移父级的顶部和左侧位置.
知道这一点,然后很容易......(使用我的小svg项目作为示例页面)
var x = $("#wrapper2").offset().left;
var y = $("#wrapper2").offset().top;
console.log('x: ' + x + ' y: ' + y);
Run Code Online (Sandbox Code Playgroud)
输出:
x: 53 y: 177
Run Code Online (Sandbox Code Playgroud)
希望它有助于你所寻找的东西.
这是offset()和position()的图像
使用XRay

使用Web Developer工具栏

我的解决方案是一个带有"变通方法"的插件:+ D. 但是作品!
jQuery.fn.getPos = function(){
var o = this[0];
var left = 0, top = 0, parentNode = null, offsetParent = null;
offsetParent = o.offsetParent;
var original = o;
var el = o;
while (el.parentNode != null) {
el = el.parentNode;
if (el.offsetParent != null) {
var considerScroll = true;
if (window.opera) {
if (el == original.parentNode || el.nodeName == "TR") {
considerScroll = false;
}
}
if (considerScroll) {
if (el.scrollTop && el.scrollTop > 0) {
top -= el.scrollTop;
}
if (el.scrollLeft && el.scrollLeft > 0) {
left -= el.scrollLeft;
}
}
}
if (el == offsetParent) {
left += o.offsetLeft;
if (el.clientLeft && el.nodeName != "TABLE") {
left += el.clientLeft;
}
top += o.offsetTop;
if (el.clientTop && el.nodeName != "TABLE") {
top += el.clientTop;
}
o = el;
if (o.offsetParent == null) {
if (o.offsetLeft) {
left += o.offsetLeft;
}
if (o.offsetTop) {
top += o.offsetTop;
}
}
offsetParent = o.offsetParent;
}
}
return {
left: left,
top: top
};
};
Run Code Online (Sandbox Code Playgroud)
用法:
var p = $("#wrapper2").getPos();
alert("top:"+p.top+"; left:"+p.left);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90196 次 |
| 最近记录: |