[英]Get SVG text element's width
I have the following SVG text element:我有以下 SVG 文本元素:
<text data-model-id="k10673" x="584" y="266" fill-opacity="1" style="font: 12px Arial,Helvetica,sans-serif; " fill="#a5d16f">BU YIL SONU</text>
It's approximately in the middle of the screen.它大约在屏幕的中间。 And I can inspect it as follows:我可以按如下方式检查它:
I need to get the width of this text.我需要获取此文本的宽度。 On chrome debugger, I can see the that the text has a width of 83.941在 chrome 调试器上,我可以看到文本的宽度为 83.941
However, I cannot get this width from my Javascript page.但是,我无法从我的 Javascript 页面获得这个宽度。 Any method related to the width returns zero, although it's correctly displayed by Chrome debugger.任何与宽度相关的方法都返回零,尽管它被 Chrome 调试器正确显示。
I get the element as follows:我得到的元素如下:
var x = document.querySelector("#k11489 > g:nth-child(27) > text:nth-child(1)")
Then, following Javascript functions all return zero or undefined:然后,以下 Javascript 函数都返回零或未定义:
x.getComputedTextLength()
x.getBBox().width
x.style.width
Also I've tried the following jQuery functions after getting the jQuery object, however, none of them returns the width either:此外,我在获取 jQuery 对象后尝试了以下 jQuery 函数,但是,它们都没有返回宽度:
x.width() //Returns the function
x.innerWidth() //Returns null
x.outerWidth() //Returns null
Note: In order to make sure that x points to the text element, I check them through the console.注意:为了确保 x 指向文本元素,我通过控制台检查它们。 Following are the snapshots of Javascript and jQuery objects:以下是 Javascript 和 jQuery 对象的快照:
How can I get this object's width in by Javascript or jQuery?如何通过 Javascript 或 jQuery 获取此对象的宽度?
Dont know if it works on textelements, but for me, the不知道它是否适用于文本元素,但对我来说,
document.querySelector('.whatever').getBoundingClientRect().width;
works, and respects current scaling of the svg.有效,并尊重 svg 的当前缩放比例。 See also this answer - adapting the accepted answers fiddle to target a text node, works for me.另请参阅此答案- 调整已接受的答案以针对文本节点,对我有用。
You can use getBBox() (which is part of SVG 1.1) to get the width of an svg element as below.您可以使用 getBBox()(它是 SVG 1.1 的一部分)来获取 svg 元素的宽度,如下所示。
$("your_jquery_selector")[0].getBBox().width.
If it's valid selector then use如果它是有效的选择器,则使用
$("#k11489 > g:nth-child(27) > text:nth-child(1)")[0].getBBox().width
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.