2013-06-05 24 views
6

是否有一種方法可以獲取客戶端的rect,以及相對於該文檔的偏移量? getBoundingClientRect()獲取相對於客戶端瀏覽器的值。我正在使用D3和jquery的高度()和寬度()正在工作(我甚至嘗試做它的window.load()),但偏移量()是。無論是JavaScript的.offsetGetBoundingClientRect,但相對於整個文檔

 return [$e.offset().top + $e.height()/2, 
      $e.offset().left + $e.width()/2] 

$ e.height()和$ e.width()都返回0

這是一個SVG元素,我只是用它來編輯我的SVG。使用D3加載/處理SVG要容易得多。該項目與數據無關,只是一張地圖。

+0

代碼請.... – Learner

+0

你有$ e.height聚填充xy道具,不是從getBoundingClientRect()返回。 height/2應該是$ e.height()/ 2 –

+0

這是一個SVG元素還是一個HTML元素?你在用D3做什麼? – nrabinowitz

回答

2

使用element.getBoundingClientRect()本身會返回topleft與您的視口相關的值,就像您發現的那樣。如果你想他們是相對於文件(而不是滾動位置的影響),您可以使用window.scrollYwindow.scrollX添加滾動位置,就像這樣:

const rect = element.getBoundingClientRect() 

rect.left     // (relative to viewport) 
rect.top     // (relative to viewport) 
rect.left + window.scrollX // (relative to document) 
rect.top + window.scrollY // (relative to document) 

Source

0

這裏是一個ES6方法,返回所有與getBoundingClientRect()相同的屬性,但是相對於整個文檔。

const getOffsetRect = (el) => 

    let rect = el.getBoundingClientRect(); 

    // add window scroll position to get the offset position 
    let left = rect.left + window.scrollX; 
    let top = rect.top + window.scrollY; 
    let right = rect.right + window.scrollX; 
    let bottom = rect.bottom + window.scrollY; 

    // polyfill missing 'x' and 'y' rect properties not returned 
    // from getBoundingClientRect() by older browsers 
    if (rect.x === undefined) let x = left; 
    else let x = rect.x + window.scrollX; 

    if (rect.y === undefined) let y = top; 
    else let y = rect.y + window.scrollY; 

    // width and height are the same 
    let width = rect.width; 
    let height = rect.height; 

    return { left, top, right, bottom, x, y, width, height }; 
}; 

注意:它也()由舊的瀏覽器

相關問題