【发布时间】:2017-01-20 08:07:17
【问题描述】:
我有一个脚本,可以在现有的<svg> 内将<text> 元素添加到我的标记中。在该新元素上运行 getBBox() 会给我一个错误。如果我在标记中包含<text> 以开始并运行等效脚本,则 getBBox 运行没有任何问题。 DOM 是否没有将我的 js 构建的 <text> 完全视为文本元素……我是否遗漏了一些“写成 '<text>”步骤?
function works() {
console.log('start "works"')
var svgElem = document.querySelector('.works');
var textElem = svgElem.querySelector('text');
var textBBox = textElem.getBBox();
console.log(textBBox);
console.log('end "works"')
}
works();
function doesntwork() {
console.log('start "doesntwork"')
var svgElem = document.querySelector('.doesntwork');
var textElem = document.createElement("text");
textElem.appendChild(svgElem.firstChild);
svgElem.appendChild(textElem);
console.log('"doesntwork" breaks after this');
var textBBox = textElem.getBBox(); // breaks the script
console.log(textBBox);
console.log('end "doesntwork"')
}
doesntwork();
<svg class="doesntwork">
not working
</svg>
<svg class="works">
<text>
working
</text>
</svg>
不太通用的第二部分:
在我的完整项目中,我实际上正在转向
<div class="target">content</div>
进入
<div class="target"><svg><text>content</text></svg></div>
使用js创建<text>和<svg>。这个想法基本上是
var targetElems = document.querySelectorAll('.target');
for (var i = 0; i < targetElems.length; ++i) { // for each target
var targetElem = targetElems[i];
var textElem = document.createElement("text"); // build a <text>
while (targetElem.firstChild) // put the target's content (which could include child elements) in the <text>
textElem.appendChild(targetElem.firstChild);
var svgElem = document.createElement("svg"); // build an <svg>
svgElem.appendChild(textElem); // put the <text> in the <svg>
targetElem.appendChild(svgElem); // put the <svg> in the target
var textBBox = textElem.getBBox(); // want to be able to get the <text>'s BBox (this currently has a breaking error)
console.log(textBBox);
}
我是否必须在每个步骤添加一个信号 - “这是<text>,这是<svg>”?
还是我把整个事情都搞错了/有没有更聪明的方法可以将.target > [content] 变成.target > svg > text > [content]?
【问题讨论】:
标签: javascript html dom svg