我試圖弄清楚如何使用以編程javascript方式生成以下內容。svg
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<rect class="bg" id="bg" x="0" y="0" width="200" height="200" fill="#0357D5"></rect>
<foreignObject x="0" y="0" width="60" height="50">
<div xmlns="http://www.w3.org/1999/xhtml">Thanks </div>
</foreignObject>
</svg>
這是我嘗試過的
const svg = document.querySelector("svg");
const svgns = "http://www.w3.org/2000/svg";
let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('x',"0");
bg.setAttribute("y","0");
bg.setAttribute("width", "200");
bg.setAttribute("height", '200');
bg.setAttribute("fill","#0357D5");
svg.appendChild(bg);
let fo = document.createElementNS(svgns, 'foreignObject');
fo.setAttribute("x", "0");
fo.setAttribute("y", "0");
fo.setAttribute("width", "60");
fo.setAttribute("height", "50");
svg.appendChild(fo);
let _div = document.createElementNS(svgns, 'div');
_div.setAttribute("xmlns", 'http://www.w3.org/1999/xhtml');
_div.textContent = 'Thanks';
svg.appendChild(_div);
fo.appendChild(_div);
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
</svg>
uj5u.com熱心網友回復:
您需要使用createElement('div')– not createElementNS,因為它不是 svg 元素。
const svg = document.querySelector("#svg");
const svgns = "http://www.w3.org/2000/svg";
let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('x',"0");
bg.setAttribute("y","0");
bg.setAttribute("width", "200");
bg.setAttribute("height", '200');
bg.setAttribute("fill","#0357D5");
svg.appendChild(bg);
let fo = document.createElementNS(svgns, 'foreignObject');
fo.setAttribute("x", "0");
fo.setAttribute("y", "0");
fo.setAttribute("width", "60");
fo.setAttribute("height", "50");
svg.appendChild(fo);
let _div = document.createElement('div');
_div.setAttribute("xmlns", 'http://www.w3.org/1999/xhtml');
_div.textContent = 'Thanks';
svg.appendChild(_div);
fo.appendChild(_div);
svg{
display:inline-block;
width:20em;
}
<svg id="svg" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451866.html
標籤:javascript svg
下一篇:通過單擊凍結svg影片
