2013-06-05 11 views
6

Có phương pháp nào để khách hàng trực tiếp cho một phần tử liên quan đến tài liệu ngoài bù trừ không? getBoundingClientRect() nhận giá trị tương đối so với trình duyệt của máy khách.GetBoundingClientRect nhưng liên quan đến toàn bộ tài liệu

Tôi đang sử dụng chiều cao D3 và jquery() hoặc chiều rộng() đang hoạt động (tôi thậm chí đã thử làm window.load()), nhưng offset() là. Không được javascripts .offset

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

$ e.height() và $ e.width() cả hai trở về 0

Đây là một yếu tố SVG, tôi chỉ sử dụng nó để chỉnh sửa SVG của tôi. Việc tải/xử lý SVG với D3 dễ dàng hơn nhiều. Dự án không liên quan đến dữ liệu, nó chỉ là một bản đồ.

+0

Mã xin vui lòng .... – Learner

+0

bạn có $ e.height(). chiều cao/2 nó phải là $ e.height()/2 –

+0

Đây có phải là phần tử SVG hay phần tử HTML không? Bạn đang làm gì với D3? – nrabinowitz

Trả lời

2

Sử dụng element.getBoundingClientRect() tự trả về topleft giá trị có liên quan đến chế độ xem, như bạn đã phát hiện. Nếu bạn muốn họ được liên quan đến các tài liệu (và không bị ảnh hưởng bởi vị trí cuộn), bạn có thể thêm các vị trí cuộn sử dụng window.scrollYwindow.scrollX, như vậy:

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

Đây là phương pháp ES6 trả về tất cả các thuộc tính giống như getBoundingClientRect() nhưng liên quan đến toàn bộ tài liệu.

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 }; 
}; 

Lưu ý: nó cũng poly-điền vào xy đạo cụ, mà không phải là trở về từ getBoundingClientRect() bằng trình duyệt cũ