在为 jTool 提供 offset (获取当前节点位置)方法时, 先后使用了两种方式进行实现, 现整理出来以作记录。
通过递归实现
function offset(element) {
var offest = {
top: 0,
left: 0
};
var _position;
getOffset(element, true);
return offest;
// 递归获取 offset, 可以考虑使用 getBoundingClientRect
function getOffset(node, init) {
// 非Element 终止递归
if (node.nodeType !== 1) {
return;
}
_position = window.getComputedStyle(node)['position'];
// position=static: 继续递归父节点
if (typeof(init) === 'undefined' && _position === 'static') {
getOffset(node.parentNode);
return;
}
offest.top = node.offsetTop + offest.top - node.scrollTop;
offest.left = node.offsetLeft + offest.left - node.scrollLeft;
// position = fixed: 获取值后退出递归
if (_position === 'fixed') {
return;
}
getOffset(node.parentNode);
}
}
// 执行offse