当我运行这段代码时,它会显示一个空白屏幕,但当我使用 chrome 中的开发人员工具更新代码时,它会显示数据。请帮忙解释一下为什么当我使用 chrome 的开发者工具更新代码时它会显示, 是否由于浏览器中的 DOM 再次运行,如果是,那么为什么不在第一次显示时出现。这是否是由于 foreignObject.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<svg id="t">
<g>
<text x="10" y="10">hello</text>
</g>
</svg>
<script>
var s = document.getElementById('t');
var g = s.childNodes[1];
console.log(g.childNodes[1].remove());
var foreign = document.createElementNS('http://www.w3.org/2000/svg',"foreignObject");
foreign.setAttribute('width', 500);
foreign.setAttribute('height', 150);
var txt = document.createElementNS('http://www.w3.org/2000/svg', 'text');
txt.setAttribute('x', '10');
txt.setAttribute('y', '10');
var t = document.createTextNode("This is a paragraph.");
txt.appendChild(t);
foreign.appendChild(txt);
g.appendChild(foreign);
</script>
</body>
</html>
最佳答案
@JabranSaeed if you want to use foroeignObject,beter to follow this method
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<svg id="t">
<g>
</g>
</svg>
<script>
var s = document.getElementById('t');
var g = s.childNodes[1];
var foreign = document.createElementNS
('http://www.w3.org/2000/svg',"foreignObject");
foreign.setAttribute('width', 500);
foreign.setAttribute('height',500);
var iDivele = document.createElement('div');
var ob = document.createTextNode("xxxx");
iDiv.appendChild(ov);
foreign.appendChild(iDivele);
g.appendChild(foreign);
</script>
</body>
</html>
关于javascript - 使用javascript在svg中动态添加外部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31231833/