JavaScript createElementNS and SVG

前端 未结 4 1657
轻奢々
轻奢々 2020-11-28 09:56

I want to create inline SVG graphics using Javascript.

However, it seems like createElementNS function applies some normalization and transforms all tags

4条回答
  •  臣服心动
    2020-11-28 10:16

    Firstly, use createElementNS, as you are doing. createElement (without NS) automatically lowercases element names inside HTML documents, according to the Mozilla documentation.

    Secondly, don't trust Google Chrome's "Inspect Element" feature here. It seems to display every element in lowercase, no matter what the actual nodeName is. Try this:

    document.createElementNS("http://www.w3.org/2000/svg", "textPath").nodeName
    // Output: "textPath"
    
    document.createElement("textPath").nodeName
    // Output: "TEXTPATH"
    

    Your problem might be an unrelated issue. For example, this code works fine in Firefox, but breaks in Chrome (12.0.742.112):

    function animateSVG() {
      var svgNS = "http://www.w3.org/2000/svg";
      var textElement = document.getElementById("TextElement");
      var amElement = document.createElementNS(svgNS, "animateMotion");
      console.log(textElement);
      console.log(amElement);
      console.log(amElement.nodeName);
      amElement.setAttribute("path", "M 0 0 L 100 100");
      amElement.setAttribute("dur", "5s");
      amElement.setAttribute("fill", "freeze");
      textElement.appendChild(amElement);
      //amElement.beginElement();
    };
    
      
        
          
            It's SVG!
            
          
        
      
    

    My issue probably has something to do with the broken handling of animateMotion in Chrome (Issue 13585).

    Your issue might be the same, or it might be another issue, but make sure you're not being fooled by the element inspector.

提交回复
热议问题