javascript - 将 nodetext 附加到 svg 元素
问题描述
我会将文本节点附加到g
svg 元素。
触发时屏幕上没有打印任何内容my function
但是当我将TextNode
元素直接附加到正文时它起作用了
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var t = document.createTextNode("Hello World");
document.body.appendChild(g);
g.appendChild(t)
}
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
此代码无需使用即可工作g
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var t = document.createTextNode("Hello World");
document.body.appendChild(t);
}
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
解决方案
您还需要创建一个文本元素并将所有内容附加到 svg 元素。在这种情况下,我使用带有 viewBox 的 svg 元素,尽管我没有为 x 和 y 属性设置任何值,但它允许我查看文本。根据您的 viewBox,您可能还需要设置这些属性。
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.textContent = "Hello World";
g.appendChild(text);
svg.appendChild(g);
}
<p>Click the button to create a Text Node.</p>
<svg id="svg" viewBox="-100 -50 200 100" width="200"></svg>
<button onclick="myFunction()">Try it</button>
推荐阅读
- angular - 如何以编程方式取消选择垫子选项?
- reactjs - TestDont - 更改用户名 - 反应
- angular - Angular v10 ngserve SSL 间歇性失败
- visual-studio - Xamarin 内置 Hot-reload 和 Live Xaml 之类的有什么区别
- javascript - 用户离线时的 NPM 加密 Diffie Hellman 密钥交换
- ios - 在 MainView 上隐藏 StatusBar 和 NavigationBar 但在 Swift 的 DetailView 上显示它
- c++ - 如何解析包含 unicode 文字的 std::string?
- python - Anaconda 导航器打开虚拟环境 jupyter
- php - 从列相同的 2 个表中选择数据,查询不太正确?
- html - chartjs tooltip html:使用数据填充工具提示