【发布时间】:2019-03-29 21:30:49
【问题描述】:
我有一个通过 JS 脚本添加到 SVG 的文本标签,并希望使该文本可编辑。
在 StackOverflow 上找到了几个解决方案:
-
创建一个 css 类并将其应用于我的 SVG 文本元素。这工作得很好,至少在 Safari 中,但 MDN https://developer.mozilla.org/en-US/docs/Web/CSS/user-modify 不推荐它 这是实际上是某人的答案的课程,不幸的是我不记得是谁的:
.editable { font-size: 0.3em; user-modify: read-write; -moz-user-modify: read-write; -webkit-user-modify: read-write; } 将 svg 包装在一个内容可编辑的 div 中(Erik 给出的答案)。这也有效,但会导致光标行为不佳,至少在 Safari 中是这样。
<div contenteditable="true">
<svg id="svgArea" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
</svg>
</div>
JS部分
function foo(x, y, w, h) {
var rect, group;
var svgPlace = document.getElementById('svgArea');
var xmlns = "http://www.w3.org/2000/svg";
group = document.createElementNS(xmlns, 'g');
svgPlace.appendChild(group);
var txtElem = document.createElementNS(xmlns, 'text');
txtElem.setAttributeNS(null, 'x', x);
txtElem.setAttributeNS(null, 'y', y * 1.25);
txtElem.setAttributeNS(null, 'fill', 'LightBlue');
txtElem.setAttributeNS(null, 'contentEditable', true); //does nothing!
txtElem.setAttributeNS(null, 'class', 'editable'); //this is the best working option at the moment
var txtVal = document.createTextNode('test');
txtElem.appendChild(txtVal);
group.appendChild(txtElem);
}
如果可能的话,我希望能够将 contentEditable 设置为属性。但最重要的是,让 SVG 文本可编辑的最佳方法是什么?
【问题讨论】:
-
document.getElementById("element").contentEditable = "true";您还可以在 HTML 元素中使用引用contenteditable="true",如下所示:<div contenteditable="true">。 -
在第二个示例中,您没有要编辑的文本元素..
-
Raymond,包裹在文本元素通过JS添加到第二个代码部分的SVG元素中。
标签: javascript html svg