2009-05-06 47 views
7

有最近在那里 胜利宣布comp.lang.javascript这个线程,但没有代码被张贴:如何查找HTML按钮或图像的坐标,跨浏览器?

上的HTML页面,你如何找到一个元素的左下角坐标(图像或按钮,说) 可靠跨浏览器和页面样式?在“Ajax in Action”(我有的副本)中提倡的方法在某些情况下在IE中似乎不起作用。为了使问题更容易,我们假设我们可以将全局文档样式设置为“传统”或“过渡”等。

请提供代码或指向代码的指针(一个适用于所有浏览器的完整函数) - 不要只是说“那很容易”,并且说明遍历DOM的内容 - 如果我想阅读那种的东西,我会回到comp.lang.javascript。如果这是重复的,请指责我,并指出我的解决方案 - 我确实试图找到它。

+2

圣(* &^。我只是看着jquery解决方案:向DOM中添加一个隐藏元素,其中包含每个可能的标记,然后对几何约定进行逆向工程。网络真是太神奇了! – 2009-05-06 12:53:25

+1

这里有龙 – 2009-05-07 16:38:41

回答

9

以我的经验,唯一安全可靠的方式得到的东西像这样的工作是使用JQuery(不用怕,它只是一个你必须包含的外部脚本文件)。然后你可以使用如下语句

$('#element').position() 

$('#element').offset() 

获得当前的坐标,它在任何工作出色,到目前为止,我遇到所有的浏览器。

1

试试这个:

var elm = document.getElementById('foo'); 
var point = {x:0,y:elm.offsetHeight}; // Change to y:0 to get the top-left 

while (elm) 
{ 
    // This will get you the position relative to the absolute container, 
    // which is what you need for positioning an element within it 
    if (elm.style.position == 'absolute') 
     break; 

    point.x += elm.offsetLeft; 
    point.y += elm.offsetTop; 

    elm = elm.offsetParent; 
} 
+0

格雷格,这是什么不工作(有时)。 – 2009-05-06 12:33:23

+0

你能举一个它不工作的具体例子吗? – Greg 2009-05-06 12:45:43

1

在jQuery中:

var jq = $('#yourElement'); 
var position = jq.offset(); 
alert('x: ' + position.left + ', y: ' + position.top); 

var bottomLeftPixelPosition = 
    { left: position.left, top: position.top + jq.height() - 1; }; 
2

我一直在使用它,适用于IE和Firefox。

 
var Target = document.getElementById('SomeID'); 
var Pos = findPos(Target); 

AnotherObj = document.getElementById('AnotherID'); 
AnotherObj .style.top = Pos[1] + "px"; 
AnotherObj .style.left = Pos[0] + "px"; 

//------------------------------------ 
function findPos(obj) { 
//---------------------------------------- 
    var curleft = curtop = 0; 
    if (obj.offsetParent) { 
    do { 
      curleft += obj.offsetLeft; 
      curtop += obj.offsetTop; 
    } while (obj = obj.offsetParent); 
    return [curleft,curtop]; 
    } 
} 
4

我发现这个解决方案从网上...这完全解决了我的问题。 请检查此链接的来源。 http://www.quirksmode.org/js/findpos.html

/** This script finds the real position, 
* so if you resize the page and run the script again, 
* it points to the correct new position of the element. 
*/ 
function findPos(obj){ 
    var curleft = 0; 
    var curtop = 0; 

    if (obj.offsetParent) { 
     do { 
     curleft += obj.offsetLeft; 
     curtop += obj.offsetTop; 
     } while (obj = obj.offsetParent); 

     return {X:curleft,Y:curtop}; 
    } 
} 

完美的作品在Firefox,IE8,歌剧(希望别人太) 感谢那些谁分享他们的知识...... 问候,

再生不良