Joh*_*ohn 10 html javascript jquery d3.js
除了偏移之外,是否有一种方法可以获取相对于文档的元素的客户端rect?getBoundingClientRect()获取相对于客户端浏览器的值.
我正在使用D3和jquery的height()或width()正在工作(我甚至尝试过做window.load()),但是offset()是.也不是javascripts .offset
return [$e.offset().top + $e.height()/2, $e.offset().left + $e.width()/2]
Run Code Online (Sandbox Code Playgroud)
$ e.height()和$ e.width()都返回0
这是一个SVG元素,我只是用它来编辑我的SVG.使用D3加载/处理SVG要容易得多.该项目与数据无关,它只是一张地图.
Ian*_*lor 12
单独使用element.getBoundingClientRect()
返回top
和left
相对于视口的值,就像您发现的那样.如果您希望它们相对于文档(并且不受滚动位置影响),您可以使用window.scrollY
和添加滚动位置window.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)
Run Code Online (Sandbox Code Playgroud)
来源.
这是一个 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 };
};
Run Code Online (Sandbox Code Playgroud)
注意:它也是 poly-fillingx
和y
props,旧浏览器不会从 getBoundingClientRect() 返回
归档时间: |
|
查看次数: |
5357 次 |
最近记录: |