jquery's append not working with svg element?

后端 未结 14 2179
北海茫月
北海茫月 2020-11-21 06:28

Assuming this:



 
 

        
相关标签:
14条回答
  • 2020-11-21 06:45

    I haven't seen someone mention this method but document.createElementNS() is helpful in this instance.

    You can create the elements using vanilla Javascript as normal DOM nodes with the correct namespace and then jQuery-ify them from there. Like so:

    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
        circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    
    var $circle = $(circle).attr({ //All your attributes });
    
    $(svg).append($circle);
    

    The only down side is that you have to create each SVG element with the right namespace individually or it won't work.

    0 讨论(0)
  • 2020-11-21 06:47

    When you pass a markup string into $, it's parsed as HTML using the browser's innerHTML property on a <div> (or other suitable container for special cases like <tr>). innerHTML can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <circle> was supposed to be in the SVG namespace.

    innerHTML is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.

    HTML5 promises to let you use <svg> without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML even though they look like part of an HTML document.

    However, for today's browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"><head>
    </head><body>
        <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
        <script type="text/javascript">
            function makeSVG(tag, attrs) {
                var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
                for (var k in attrs)
                    el.setAttribute(k, attrs[k]);
                return el;
            }
    
            var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
            document.getElementById('s').appendChild(circle);
            circle.onmousedown= function() {
                alert('hello');
            };
        </script>
    </body></html>
    

    *: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML, then transfer it to the desired target. It'll likely be a bit slower though:

    <script type="text/javascript"><![CDATA[
        function parseSVG(s) {
            var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
            div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
            var frag= document.createDocumentFragment();
            while (div.firstChild.firstChild)
                frag.appendChild(div.firstChild.firstChild);
            return frag;
        }
    
        document.getElementById('s').appendChild(parseSVG(
            '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
        ));
    ]]></script>
    

    **: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.

    0 讨论(0)
  • 2020-11-21 06:47

    The accepted answer by Bobince is a short, portable solution. If you need to not only append SVG but also manipulate it, you could try the JavaScript library "Pablo" (I wrote it). It will feel familiar to jQuery users.

    Your code example would then look like:

    $(document).ready(function(){
        Pablo("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
    });
    

    You can also create SVG elements on the fly, without specifying markup:

    var circle = Pablo.circle({
        cx:100,
        cy:50,
        r:40
    }).appendTo('svg');
    
    0 讨论(0)
  • 2020-11-21 06:48

    This is working for me today with FF 57:

    function () {
        // JQuery, today, doesn't play well with adding SVG elements - tricks required
        $(selector_to_node_in_svg_doc).parent().prepend($(this).clone().text("Your"));
        $(selector_to_node_in_svg_doc).text("New").attr("x", "340").text("New")
            .attr('stroke', 'blue').attr("style", "text-decoration: line-through");
    }
    

    Makes:

    0 讨论(0)
  • 2020-11-21 06:49

    JQuery can't append elements to <svg> (it does seem to add them in the DOM explorer, but not on the screen).

    One workaround is to append an <svg> with all of the elements that you need to the page, and then modify the attributes of the elements using .attr().

    $('body')
      .append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
      .mousemove( function (e) {
          $("#c").attr({
              cx: e.pageX,
              cy: e.pageY
          });
      });
    

    http://jsfiddle.net/8FBjb/1/

    0 讨论(0)
  • 2020-11-21 06:51

    Found an easy way which works with all browsers I have (Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)) :

    // Clean svg content (if you want to update the svg's objects)
    // Note : .html('') doesn't works for svg in some browsers
    $('#svgObject').empty();
    // add some objects
    $('#svgObject').append('<polygon class="svgStyle" points="10,10 50,10 50,50 10,50 10,10" />');
    $('#svgObject').append('<circle class="svgStyle" cx="100" cy="30" r="25"/>');
    
    // Magic happens here: refresh DOM (you must refresh svg's parent for Edge/IE and Safari)
    $('#svgContainer').html($('#svgContainer').html());
    .svgStyle
    {
      fill:cornflowerblue;
      fill-opacity:0.2;
      stroke-width:2;
      stroke-dasharray:5,5;
      stroke:black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="svgContainer">
      <svg id="svgObject" height="100" width="200"></svg>
    </div>
    
    <span>It works if two shapes (one square and one circle) are displayed above.</span>

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