JS动态创建SVG元素并绑定事件

  var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute("width", "800");
    svg.setAttribute("height", "500");
    svg.addEventListener("load", function () { alert('loaded'); });
    document.body.appendChild(svg);

以上代码可创建SVG容器并追加到body元素下,如果要添加元素,使用以下代码:

   var r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    r.setAttribute("fill", "#120045");
    r.setAttribute("x", "1");
    r.setAttribute("y", "1");
    r.setAttribute("width", "50%");
    r.setAttribute("height", "50%");
    r.addEventListener("click", function () { alert('clicked'); });
    svg.appendChild(r);

 

posted @ 2014-06-16 12:38  yzeng  阅读(6891)  评论(0编辑  收藏  举报