如何使用JavaScript创建SVG元素?我试过这个:
var svg = document.createElement('SVG');
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.setAttribute('version', '1.1');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
document.body.appendChild(svg);
Run Code Online (Sandbox Code Playgroud)
然而,它创建了一个零宽度和零高度的SVG元素.
我是从JavaScript动态创建SVG元素.它适用于像矩形这样的可视对象,但是我在生成正常运行的xlink时遇到了麻烦.在下面的示例中,第一个矩形(静态定义)在单击时正常工作,但另外两个(在JavaScript中创建)忽略了点击...即使检查Chrome中的元素似乎显示相同的结构.
我已经看到了多个类似的问题,但没有一个能够解决这个问题.我发现最接近的是[ 通过JS在svg中添加图像命名空间仍然没有向我显示图片 ]但是这不起作用(如下所述).我的目标是纯粹使用JavaScript,而不依赖于JQuery或其他库.
<!-- Static - this rectangle draws and responds to click -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag">
<a xlink:href="page2.html" id="buttonTemplate">
<rect x="20" y="20" width="200" height="50" fill="red" class="linkRect"/>
</a>
</svg>
<script>
var svgElement = document.getElementById ("svgTag");
// Dynamic attempt #1 - draws but doesn't respond to clicks
var link = document.createElementNS("http://www.w3.org/2000/svg", "a"); // using http://www.w3.org/1999/xlink for NS prevents drawing
link.setAttribute ("xlink:href", "page2.html"); // no improvement with setAttributeNS
svgElement.appendChild(link);
var box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
box.setAttribute("x", 30);
box.setAttribute("y", 30);
box.setAttribute("width", 200); …Run Code Online (Sandbox Code Playgroud) 我试图仅在页面加载时或加载后创建SVG标签结构。
这个请求可能看起来很奇怪,但这是必需的,因为大多数html标记是由编译的创作软件应用程序生成的,因此我无法对其进行篡改。我只能根据需要“注入” JavaScript来创建其他资产(例如:Div)。
参见下面的标记。[为清晰起见,省略了html标记的部分。]
<html>
....
<script>
function run() {
var newSvg = document.getElementById('myDiv');
newSvg.outerHTML+='<svg style="position:absolute;z-index:10;margin:0;padding:0;top:0em;left:0.5em" onclick="go()" width="100" height=100><circle cx="400" cy="400" r="40" stroke="red" stroke-width="4" fill="blue" />';
}
</script>
<body>
....
<div id="myDiv"></div>
....
<script>
run();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果我手动将SVG标记放置在目标位置,则页面和SVG会正确呈现。如果我尝试动态创建标记,那么我将一无所获。
当我在页面加载后查看html源代码时,该功能应该已经为SVG创建了标记。
我试图通过一个<body onLoad="run()">事件来做,但它也不起作用。
注意:当我需要动态创建新的DIV时,此功能运行良好。
我究竟做错了什么?在此先感谢所有人。