我正在为 Power BI 构建一个用 TypeScript 编写的自定义视觉对象。在我的类的构造函数中,我编写 this.svg = d3.select(this.target).append("svg").attr("id", "svg");
(this .target
只是包含一个标准的 HTML 元素,这对于问题来说并不重要)。
我的问题是,使用this.svg
,我怎样才能获得原始的SVG元素?从谷歌搜索来看,我似乎应该能够使用 this.svg.node()
,但是一定有一些微妙的事情发生,使得它与“true”元素不同......
当我运行 console.log(this.svg.node())
时,其输出与 console.log(document.getElementById("svg"))< 完全相同
在 Chrome 的开发者窗口中,这样就可以了。
但是,使用表达式 this.svg.node().getBoundingClientRect()
会导致我的 TypeScript 无法编译,因为出现错误 Property 'getBoundingClientRect' does not exit on type 'Node' '
,而 document.getElementById("svg").getBoundingClientRect()
返回正确的值。
如何获取 this.svg
引用的真实的原始 DOM 元素?
我使用的是 d3 v3。
最佳答案
.node()
正在返回真实元素,这里的问题是在其他情况下 .node()
可以返回除 之外的其他类型的对象Element
,因此 typescript 编译器无法知道它肯定有 getBoundingClientRect()
函数。
解决方案是将对象转换为 Element
类型:
var svgElement = this.svg.node() as Element;
var boundingRect = svgElement.getBoundingClientRect();
关于javascript - 从 d3 选择中获取原始元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45482615/