获取元素在页面中的绝对位置

603 阅读1分钟
// 获取页面元素的绝对位置
export function offset(el) {
// getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性
let rect = el.getBoundingClientRect()
let pos = {
    left: rect.left,
    top: rect.top
}
// ownerDocument 属性返回节点所属的 Document 。
// 在 HTML 中,HTML 文档本身始终是元素的 ownerDocument。
let doc = el.ownerDocument
// 每个document都有自己的window对象, 不能直接用window。如iframe、window.open、chrome plugin都有自己独立的window对象
// parentwindow是兼容ie的写法, 在其它浏览器都写作defaultview, defaultview就是当前文档  
//所属的window对象
let w = doc.defaultView || doc.parentWindow
pos.left += getScroll(w)
pos.top += getScroll(w, 1)
return pos

}

// 获取浏览器水平、垂直方向的滚动距离, top等效于true则获取垂直, 否则获取水平
export function getScroll(w, top?: number) {
let ret = w['page' + (top ? 'Y' : 'X') + 'Offset']
let method = 'scroll' + (top ? 'Top' : 'Left')
if (typeof ret !== 'number') {
    let d = w.document
    ret = d.documentElement[method]
    if (typeof ret !== 'number') {
        ret = d.body[method]
    }
}
return ret

}

这个有什么用呢, 用处还是挺多的吧