javascript - 在没有jquery的情况下将g标签添加到svg标签中
问题描述
我有这段代码中的 svg 元素
let chartSVG = ReactDOM.findDOMNode(this.refChart).children[0];
我想在该 chartSVG 中添加一个包含 g 标签的水印。
解决方案
应该是使用createElementNS
and的基本 DOM 操作appendChild()
:
const xmlns = "http://www.w3.org/2000/svg";
const rect = document.createElementNS(xmlns, 'rect');
rect.setAttributeNS (null, "width", 50);
rect.setAttributeNS (null, "height", 50);
const g = document.createElementNS(xmlns, 'g');
g.appendChild(rect);
const svg = document.getElementById('svg');
svg.appendChild(g);
<svg id="svg"></svg>
或者,如果您将 SVG 内容作为字符串,则可以使用 aDOMParser()
并导入片段:
const g = new DOMParser().parseFromString(
'<g xmlns="http://www.w3.org/2000/svg"><rect width="50" height="50"/></g>',
'application/xml');
const svg = document.getElementById('svg');
svg.appendChild(svg.ownerDocument.importNode(g.documentElement, true));
<svg id="svg"></svg>
推荐阅读
- javascript - 错误:EACCES:权限被拒绝,打开“/Users/me/.yarnrc”
- typescript - 如何制作具有扩展基础的不同类型的地图?
- python-3.x - Httprequest 没有属性“_read_started”
- javascript - 我无法使用变量设置我的电子窗口大小
- docker - 在 Linux 上的“localhost”访问 minikube 中正在运行的应用程序
- android - 如何使用房间数据库中的实体填充片段?
- batch-file - 如何运行 DISKPART 脚本并在批处理中显示输出
- javascript - UglifyJS:使用可选链接语法时出错
- node.js - 如何在 NestJS 中使用节点加密来消化二进制文件
- javascript - 如何优雅地编写和处理 NodeJS Promise