日期:2014-05-17  浏览次数:20509 次

获得html控件的绝对位置

使用offsetTop和offsetLeft只能获得其相对于父窗口(或其他控件)的位置,要是想获得其相对于浏览器左上角的坐标值就要采用一个函数。

//获取元素的纵坐标
    function getTop(e){
    var offset=e.offsetTop;
    if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
    return offset;
    }
    //获取元素的横坐标
    function getLeft(e){
    var offset=e.offsetLeft;
    if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
    return offset;
    }
e是控件对象,通过递归迭代,一步步获得offset绝对位置。