Is it possible to work with jquery and Svg directly (no plugins)?

前端 未结 3 756
夕颜
夕颜 2020-12-10 04:41

I\'m trying to work with Jquery and Svg together. But I don´t want to use any plugin.

The problem I am dealing now is that when I try to work using the traditional

相关标签:
3条回答
  • 2020-12-10 04:55

    Haven't been able to try, but I bet this would work. Instead of

    $(mySvg).append("<circle />");
    

    Do

    $(mySvg).append(document.createElementNS("http://www.w3.org/2000/svg", "circle"));
    

    If you plan on doing this more than once, maybe

    function svgEl(tagName) {
        return document.createElementNS("http://www.w3.org/2000/svg", tagName);
    }
    
    $(mySvg).append(svgEl("circle"));
    

    This is the same as the old trick of getting better performance via $(document.createElement("div")) instead of $("<div />").

    0 讨论(0)
  • 2020-12-10 05:00

    Don't use jQuery and SVG together. jQuery was designed for DOM manipulation, Raphael is designed for SVG manipulation.

    Use Raphael which is a JavaScript library which does SVG for you.

    You really shouldn't do everything the hard way, it's just going to cause problems.

    0 讨论(0)
  • 2020-12-10 05:03

    This works in Chrome 11. Haven't tried in other browsers.

    $(mySvg).append("<svg><circle /></svg>");
    $(mySvg).find("circle").unwrap();
    $(mySvg).find("circle").attr("cx","160");
    $(mySvg).find("circle").attr("cy","70");
    $(mySvg).find("circle").attr("r","30");
    $(mySvg).find("circle").attr("class","class1" );
    

    As I understand it, jQuery parses html by passing the string to the browser's native HTML parser. The HTML parsing rules assign a namespace to the element based on its name and its ancestor elements, so to get the circle element into the svg namespace it needs to be parsed inside an svg element.

    So here, it is parsed and appended inside the <svg> element and then unwrap is called to remove the extra svg element created. This append-and-unwrap pattern is somewhat ugly, and I expect that someone with better jQuery knowledge can find a more elegant solution, but the concept is clear enough.

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