有帮助?打赏吧!

【转载】动态新增svg节点

原文地址:http://blog.csdn.net/tomatomas/article/details/50442497

原文作者:番茄大圣

 

 

创建svg节点时,要使用createElementNS函数并传入节点名称的命名空间。

否则创建出来的节点默认为html dom而不是svg dom。

这样的话,将其append到svg节点下时,不会显示。

<html>  
<head>  
<meta charset="utf-8">  
<title>无标题文档</title>  
<meta content="width=device-width;initial-scale=1">   
<script>  
    function onLoad(){  
        var mysvg = document.getElementById("svg_my");  
        var rectObj = document.createElementNS("http://www.w3.org/2000/svg","rect");  
        if(rectObj){  
            rectObj.setAttribute("width",100);  
            rectObj.setAttribute("height",100);  
            rectObj.setAttribute("style","fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)");  
            mysvg.appendChild(rectObj);  
            alert("hello");  
        }  
    }  
    window.onload = onLoad;  
</script>  
</head>  
  
<body>  
    <svg id="svg_my" style="border:1px solid #000;width:200px;height:200px" version="1.1" xmlns="http://www.w3.org/2000/svg">  
          
    </svg>  
</body>  
</html>  

 

posted @ 2016-11-24 15:46  luoeeyang  Views(1214)  Comments(0Edit  收藏  举报