【问题标题】:Can't set color of SVG text through JavaScript无法通过 JavaScript 设置 SVG 文本的颜色
【发布时间】:2021-05-13 13:04:59
【问题描述】:

我使用 javascript 创建 svg 文本,然后设置属性,但其中一些无法正常工作:

      let svgns = "http://www.w3.org/2000/svg";
      let container = document.getElementById("mySVG");
      var text = document.createElementNS(svgns, "text");
      text.setAttributeNS(null, "x", 30);
      text.setAttributeNS(null, "y", 20);
      text.textContent = "Hello!";
      text.style.fontSize = "50"; 
      text.style.fontFamily = "Arial";
      text.style.color = "red"; // does'nt display
      text.style.textIdent = "500px"; // does'nt store in the attributes
      text.style.textShadow = "5px 5px 10px pink";
      text.style.textOrientation = "upright";
      text.style.textOverflow = "ellipsis";
      text.style.textRendering = "auto";
      text.style.writingMode = "vertical-rl";
      container.appendChild(text);

然后我检查了属性

      for (let prop in text.style) {
        let val = text.style[prop];
        console.log(`${prop} = ${val}`);
      }

控制台结果是:

所以最后'红色'存储在颜色属性中,但不显示(浏览器中的文本仍然是黑色 - Chrome,版本 90.0.4430.93(官方构建)(x86_64 )), 并且 text-indent 也没有值(其他属性表现良好)。

有什么线索吗?

【问题讨论】:

  • 我有同样的问题text.style.border = "solid";它在属性中但没有显示

标签: javascript svg


【解决方案1】:

SVG 文本不是 HTML 文本。它有一组不同的 CSS 属性——其中一些与 HTML 文本重叠,但不是全部——例如SVG 文本没有边框属性。而且没有“颜色”属性(你想要“填充”)

请阅读有关文本元素的文档:

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text

【讨论】:

  • 我不完全明白的是,如果我执行 console.log(text) 我会得到 "Hello!" 如果我​​在 HTML 中复制/粘贴它,它会显示边框和正确的颜色 ...
  • 如果将其复制并粘贴到 HTML 中,文本元素将被视为未知的 HTML 元素:stackoverflow.com/questions/10830682/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2014-06-03
  • 2016-08-29
  • 1970-01-01
  • 2021-03-08
  • 2019-04-10
相关资源
最近更新 更多