好时光论坛用户。请告诉我如何考虑字体参数(大小,类型,样式)来获取元素的大小
let tagText = document.createElementNS("http://www.w3.org/2000/svg", "text");
tagText.setAttributeNS(null, "font-size", 18);
tagText.setAttributeNS(null, "font-weight", 400);
tagText.setAttributeNS(null, "font-family", "Roboto");
tagText.innerHTML = 'Some text ...';
// where ViewPort ??
let widthTitle = tagText.getBBox().width;
console.log('width title: ', widthTitle); // return 0;
更新遗憾的是,添加后更改大小并不是很方便,因为您必须找到所有元素并按比例更改位置。 (我最初设置了模板引擎(handlebars.js),在那里我传递了必要的参数,它自动构建了一个带尺寸的元素(问题只在于获取长度文本)。
OP正在评论:
我根据收到的数据生成一个svg对象。生成的文本可以有不同的长度,我需要计算它的大小,以便在宽度上正确生成对象。
正如我已经评论过的那样:在这种情况下,您可以从svg所需的任何大小开始,附加文本,获取文本的大小,例如使用textLength
属性,然后更改svg元素的大小
let tagText = document.createElementNS("http://www.w3.org/2000/svg", "text");
tagText.setAttributeNS(null, "y", 20);
tagText.textContent = 'Some text ...';
svg.appendChild(tagText)
let widthTitle = tagText.textLength.baseVal.value;
svg.setAttributeNS(null,"viewBox",`0 0 ${widthTitle} 25`)
text{font-size:18px;
font-weight:400;
font-family:Roboto
}
svg{border:1px solid; width:200px;}
<svg id="svg"></svg>
假设元素已插入到网页中,您可以使用以下内容:
getComputedStyle(tagText).width
但是,如果您没有自己指定宽度(例如,使用CSS),则在您的情况下,默认值为auto
。
如果是这种情况,您可以尝试查看元素父级的宽度,执行以下操作:
tagText.parentElement.offsetWidth