Home  >  Article  >  Web Front-end  >  js实现jquery的offset()方法实例_javascript技巧

js实现jquery的offset()方法实例_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:21:191148browse

本文实例讲述了js实现jquery的offset()方法。分享给大家供大家参考。具体分析如下:

用过jQuery的offset()的同学都知道offset().top或offset().left很方便地取得元素相对于整个页面的偏移。

而在js里,没有这样直接的方法,节点的属性offsetTop可以获得该节点相对于父节点的相对偏移,但不能直接获得其绝对偏移,我们可用节点逐层递归向上来相加offsetTop来获得绝对偏移。

复制代码 代码如下:
function getOffset(Node, offset) {
    if (!offset) {
        offset = {};
        offset.top = 0;
        offset.left = 0;
    }

    if (Node == document.body) {//当该节点为body节点时,结束递归
        return offset;
    }

    offset.top += Node.offsetTop;
    offset.left += Node.offsetLeft;

    return getOffset(Node.parentNode, offset);//向上累加offset里的值
}


 

使用时,则如:

复制代码 代码如下:
var a = document.getElementById('a');
//getOffset(a).top
//getOffset(a).left

希望本文所述对大家的javascript程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn