GetBoundingClientRect但相对于整个文档 [英] GetBoundingClientRect but relative to the entire document

查看:43
本文介绍了GetBoundingClientRect但相对于整个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了偏移量之外,是否有一种方法可以获取与文档有关的元素的 client rect ? getBoundingClientRect()获取相对于客户端浏览器的值.

Is there a method for getting the client rect for an element relative to the document besides offset? getBoundingClientRect() gets the value relative to the client's browser.

我正在使用 D3 jQuery的 height() width()都正常工作(我我们甚至尝试过 window.load()),但 offset()是.javascripts.offset都不是

I'm using D3 and jQuery's height() nor width() are working (I've even tried doing it window.load()), but offset() is. Neither are javascripts .offset

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

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

这是一个 SVG 元素,我只是用它来编辑我的 SVG .使用 D3 加载/处理SVG更加容易.该项目与数据无关,只是一张地图.

It's an SVG element, I'm just using it to edit my SVG. It's much easier to load/handle SVG's with D3. The project is not data related, it's just a map.

推荐答案

单独使用 element.getBoundingClientRect()返回 top left 相对于视口的值,就像您发现的那样.如果希望它们相对于文档(不受滚动位置的影响),则可以使用 window.scrollY window.scrollX 添加滚动位置,例如所以:

Using element.getBoundingClientRect() by itself returns top and left values that are relative to the viewport, like you discovered. If you want them to be relative to the document (and not be affected by scroll position), you can add the scroll position using window.scrollY and window.scrollX, like so:

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)

.

这篇关于GetBoundingClientRect但相对于整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆