首页 > 解决方案 > 使用 JavaScript 创建动态 SVG - 使用 IE11 支持向 textContent 添加额外间距

问题描述

我正在使用 JS 创建一个 SVG 图像,并且有一个带有文本的文本元素,我一直在尝试添加间距。似乎元素对象textContent使用了文字文本,这是有道理的,但我无法使用innerHTML,因为不幸的是 IE11 不支持 SVG。我已经尝试过 了,但这也只是显示为文字文本......我也只是直接在字符串中添加了更多间距,即。**** **** ****但是除了第一个空间之外的所有内容都被剥离了。

字符串只是**** **** ****,我想在星号组之间有一些额外的空格。

我知道我可以为每个组创建单独的元素,但如果可能的话,我想避免它......我没有发布正在构建的图像的全部内容,但已经添加了很多元素,所以我我想我会检查是否有可能避免这种情况。

代码:

var container = document.getElementById('container');
var NS = 'http://www.w3.org/2000/svg';

var cardSVG = document.createElementNS(NS, 'svg');

let ccMasking = document.createElementNS(this.NS, 'text');
ccMasking.setAttributeNS(null, 'x', '34');
ccMasking.setAttributeNS(null, 'y', '19.2');
ccMasking.setAttributeNS(null, 'fill', '#fff');
ccMasking.setAttributeNS(null, 'style', 'font-size: 5px');

// Here's the string I'm trying to add space to
ccMasking.textContent = '**** **** ****';

// rest of the svg
cardSVG.setAttributeNS(null, 'viewBox', '0 0 95 70');
cardSVG.setAttributeNS(null, 'id', 'Layer_1');
cardSVG.setAttributeNS(null, 'data-name', 'Layer 1');

var rect1 = document.createElementNS(NS, 'rect');
rect1.setAttributeNS(null, 'fill', '#3CABD9');
rect1.setAttributeNS(null, 'x', '2.55');
rect1.setAttributeNS(null, 'y', '2.71');
rect1.setAttributeNS(null, 'width', '90');
rect1.setAttributeNS(null, 'height', '65');
rect1.setAttributeNS(null, 'rx', '3.35');


cardSVG.appendChild(rect1);
cardSVG.appendChild(ccMasking);
container.appendChild(cardSVG);
<div id="container"></div>

我也试过

ccMasking.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');

ccMasking.textContent = '****   ****      ****';

但这不适用于 IE11。

标签: javascripthtml

解决方案


推荐阅读