簡體   English   中英

將節點文本附加到 svg 元素

[英]Append nodetext to svg element

我會將一個 textnode 附加到一個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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM