How can I add a SVG graphic dynamically using javascript or jquery?

后端 未结 4 972
粉色の甜心
粉色の甜心 2021-01-14 02:04

I am trying to create a SVG tag structure only when or after page loads.

This request may seem strange but this is needed since most of the html markup is generated

相关标签:
4条回答
  • 2021-01-14 02:13

    Your svg dimensions ( 100 x 100 ) are smaller than the position of your circle.

    $(document).ready(function() {
      $('#myDiv').append('<svg  style="position:absolute;z-index:10;margin:0;padding:0;top:0em;left:0.5em" onclick="go()" width="100" height=100><circle cx="4" cy="4" r="4" stroke="red" stroke-width="4" fill="blue" /></svg>');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myDiv"></div>

    0 讨论(0)
  • 2021-01-14 02:14

    what you are doing is perfectly fine. There are some small flaws in your svg wich prevents it from showing up.

    1. as t1nr2y points out, use the propper namespace (xmlns="http://www.w3.org/2000/svg")
    2. the svg's height attribute is missing the quotes (height="100")
    3. your svg elements is not closed (missing </svg>)
    4. your circle is way outside your viewport (width="100" height="100" but cx="400" cy="400")

    var newSvg = document.getElementById('myDiv');
    newSvg.outerHTML += '<svg xmlns="http://www.w3.org/2000/svg" style="position:absolute;z-index:10;margin:0;padding:0;top:0em;left:0.5em" onclick="go()" width="100" height="100"><circle cx="40" cy="40" r="40" stroke="red" stroke-width="4" fill="blue" /></svg>';
    <div id="myDiv"></div>

    0 讨论(0)
  • 2021-01-14 02:21

    The javascript for SVG is a little different, since they are in different namespaces. On quick research, I couldn't find exactly where I learned this, but I did find an old SO question which does show the how it is created a little differently. Since I haven't personally researched it, I can only suggest that the outerHTML function doesn't work, and you must find the SVG namespace equivalent. Try researching on w3.org site for more info on this.

    Edit: After further research, please try creating your SVG element (rather than using a string).

    For example:

      var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      svg.setAttribute("width", "640");
      ...
      document.getElementById("div").appendChild(svg);
    
    0 讨论(0)
  • 2021-01-14 02:22
     var newSvg = document.getElementById('myDiv');
    newSvg.innerHTML += ``;
    

    This works well across all browsers.

    0 讨论(0)
提交回复
热议问题