我想使用纯 JavaScript 在 SVG 中创建 foreignObject。
我不知道为什么它不起作用。
我的异物在 <g>
中元素。里面是一个简单的 div。
我尝试使用 "requiredExtensions"
和 "xmlns"
我以为我的 div 在窗外的某个地方,但我检查了 getBoundingClientRect().left;
但事实并非如此。
我的代码在这里:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SVG TEST</title>
<style>
</style>
<script>
function init(){
var svg = document.getElementsByTagName('svg')[0]; //Get svg element
svg.setAttribute("xmlns","http://www.w3.org/2000/svg");
var g=document.createElementNS("http://www.w3.org/2000/svg", 'g'); //Create a g element in SVG's namespace
g.setAttribute("x",0); //Set g dat
g.setAttribute("y",0); //Set g dat
svg.appendChild(g);
var newNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignobject'); //Create a rect in SVG's namespace
newNode.setAttribute("x",0); //Set rect data
newNode.setAttribute("y",0); //Set rect data
newNode.setAttribute("width","180"); //Set rect data
newNode.setAttribute("height","80"); //Set rect data
g.appendChild(newNode);
var f=newNode;
var newDiv = document.createElement('div');
var divIdName = "div_1";
newDiv.setAttribute('id',divIdName);
newDiv.innerHTML = "First";
f.appendChild(newDiv);
}
</script>
</head>
<body onload="init()">
<svg id="svg" width="300px" height="300px"/>
</body>
</html>
最佳答案
SVG 区分大小写,因此您必须创建一个 foreignObject 元素而不是 foreignobject 元素。
还有一些其他的小问题:
- 设置一个 xmlns 属性什么都不做
-
<g>
元素没有 x 和 y 属性 - foreignObject 元素上的 x 和 y 默认为 0,因此它们也可以省略
关于javascript - 使用javascript在svg中创建foreignObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174412/