【问题标题】:How can I make SVG text editable?如何使 SVG 文本可编辑?
【发布时间】:2019-03-29 21:30:49
【问题描述】:

我有一个通过 JS 脚本添加到 SVG 的文本标签,并希望使该文本可编辑。

在 StackOverflow 上找到了几个解决方案:

  1. 创建一个 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;
    }
    
  2. 将 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",如下所示:&lt;div contenteditable="true"&gt;
  • 在第二个示例中,您没有要编辑的文本元素..
  • Raymond,包裹在 周围的
    可以工作,但会产生奇怪的光标行为。我无法将 contentEditable 设置为 'true' 才能工作。这是我试过的,我做错了吗?:document.getElementsByTagName("text")[0].contentEditable='true'
  • 文本元素通过JS添加到第二个代码部分的SVG元素中。

标签: javascript html svg


【解决方案1】:

@Raymond 评论是正确答案,但由于您仍有问题,我写了一个示例。

document.getElementById("svgWrapper").contentEditable = "true";
<div id="svgWrapper">
  <svg id="svgArea" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  </svg>
</div>

【讨论】:

  • 感谢马苏德和大家。该答案已经在 StackOverflow 上,并在我的问题中列为可能的解决方案之一。它会产生奇怪的光标行为。寻找另一种方式,如果有的话。
【解决方案2】:

我最终通过将输入标签放置在一个外来对象中来解决这个问题,该外来对象被添加到一个 SVG 组中。这适用于 Safari,所以我想在这里发布它,以防其他人遇到同样的事情。

<svg>
<g>
<foreignobject>
<input></input>
</foreignobject>
</g>
</svg>

如果需要使用JS添加:

function addSvg(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);

// solution
let foreigner = document.createElementNS(xmlns, "foreignObject");
foreigner.setAttributeNS(null, "x", x);
foreigner.setAttributeNS(null, "y", y);
foreigner.setAttributeNS(null, "width", w);
foreigner.setAttributeNS(null, "height", h);
group.appendChild(foreigner);

let txt = document.createElement('input');
foreigner.appendChild(txt);

}

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签