GetBoundingClientRect,但相对于整个文档
GetBoundingClientRect but relative to the entire document
是否有一种方法可以获得相对于文档的元素的客户端rectgetBoundingClientRect()
获取相对于客户端浏览器的值。
我使用的是D3
和jQuery的 height()
和width()
都在工作(我甚至尝试过做window.load()
),但offset()
是。javascript .offset
return [$e.offset().top + $e.height()/2, $e.offset().left + $e.width()/2]
$e.height()
和$e.width()
都返回0
D3
加载/处理SVG要容易得多。这个项目与数据无关,它只是一个地图。
使用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)
。
这是一个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
let x = rect.x === undefined ? left : rect.x + window.scrollX;
let y = rect.y === undefined ? top : 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 };
};
注意:它也多元填充x
和y
的道具,这是不返回从getBoundingClientRect()由旧浏览器
相关文章:
- 使用promise和mongoose对文档进行排序
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- Ajax请求文档就绪会导致jquery加载缓慢
- MongoDB (php) - 以数组而不是多个属性的形式返回文档属性
- 谷歌文档表面引擎
- 来自文档或下一个静态父级的事件委派
- 如何将childNodes用于XML文档
- 文档就绪提供了错误的选择器高度
- 将当前用户的 ID 推送到 meteorjs 中集合/文档的内部数组
- 未捕获的语法错误:无法在“文档”上执行“查询选择器”
- BrowserId登录请求在文档加载时被调用
- 从Javascript和Php变量创建Html模板文档
- 如何通过谷歌应用程序脚本从谷歌文档中的位置确定命名范围
- 在jquery文档准备好之前加载Modernizr
- 有没有办法使 ID 对于页面上的任何元素而不是文档的唯一性
- 更新文档,但出现错误:对于未定义的值,强制转换为字符串失败
- 对于文档中的变量(Javascript)
- Ajax响应对于word文档为空,对于txt和pdf则为空
- 文档.querySelector对于标准模式iframe在quirks模式父模式下运行是未定义的
- “文档.Write '适合查找与当前运行的脚本相关联的元素