查找元素的偏移客户端位置 [英] Finding the offset client position of an element

查看:94
本文介绍了查找元素的偏移客户端位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Javascript查找元素的偏移客户位置? (我假设可以用BHO或Gecko/NPAPI编写相同的代码).

How to find the offset client position of an element using Javascript? (I assume the same code can be written in a BHO or Gecko/NPAPI).

我面临的问题是一种找出元素的偏移客户位置的方法. e.srcElement.offsetX/Y并不总是给出正确的值(clientX/Y也是如此).在某些情况下,我们还需要考虑父元素滚动.

The problem I am facing is a way to find out the offset client position of the element. The e.srcElement.offsetX/Y does not give the correct value always (same goes for clientX/Y). In some cases we also need to consider the parent element scroll.

我们一般如何做到这一点?有一个简单的方法吗?

How do we do this in general? Is there an easy way for this?

推荐答案

function getElementTop ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {   
        elem = document.getElementById ( Elem );
    } 
    else if ( document.all ) 
    {
        elem = document.all[Elem];
    }           

    yPos = elem.offsetTop;
    tempEl = elem.offsetParent;

    while ( tempEl != null ) 
    {
        yPos += tempEl.offsetTop;
        tempEl = tempEl.offsetParent;
    }  

    return yPos;
}   


function getElementLeft ( Elem ) 
{
    var elem;

    if ( document.getElementById ) 
    {
        var elem = document.getElementById ( Elem );
    } 
    else if ( document.all )
    {
        var elem = document.all[Elem];
    }           

    xPos = elem.offsetLeft;
    tempEl = elem.offsetParent;         

    while ( tempEl != null ) 
    {
        xPos += tempEl.offsetLeft;
        tempEl = tempEl.offsetParent;
    }           
    return xPos;
}

将元素ID传递给函数.

Pass the element id to the functions.

这篇关于查找元素的偏移客户端位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆