document.createElementNS

使用document.createElement建立svg元素時,會發現一個詭異的現象,svg元素沒法在頁面上顯示,可是經過調試器,能夠看到該svg元素的存在。html

例如:運行如下代碼app

<body>
<svg
  xmlns="http://www.w3.org/2000/svg"
  version="1.1"
  width="100%"
  height="100%"
  id="svg"
>
  <defs>
    <marker
      id="markerArrow"
      markerWidth="10"
      markerHeight="10"
      refX="2"
      refY="6"
      orient="auto"
    >
      <path d="M2,2 L2,10 L10,6 L2,2" fill="rgba(207, 219, 230, 1)" />
    </marker>
  </defs>
</svg>
<script>
  const path = document.createElement("path");
  path.setAttribute("d", "M105,72 C105,100 105,100 173,100");
  path.setAttribute("fill", "none");
  path.setAttribute("stroke-width", "2px");
  path.setAttribute("stroke", "rgba(207, 219, 230, 1)");
  path.setAttribute("marker-end", "url(#markerArrow)");
  document.getElementById("svg").appendChild(path);
</script>
</body>

頁面上沒法顯示path元素,可是可在調試器中看到該元素的存在。
image.pngsvg

解決方法是用document.createElementNS代替document.createElement,由於XML是有命名空間的。url

const path = document.createElementNS(
  "http://www.w3.org/2000/svg",
  "path"
);

document.createElementNS

document.createElementNS與document.createElement相似,也用於建立標籤節點,只是它須要一個額外的命名空間URI做爲參數。此命名空間用於標識該節點屬於哪一種XML類型。spa

有效的命名空間URI調試

  • HTML: http://www.w3.org/1999/xhtml
  • SVG:http://www.w3.org/2000/svg
  • XBL:http://www.mozilla.org/xbl
  • XUL:http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul

命名空間爲何是必須的

一個xml文檔可能包含多個軟件模塊的元素和屬性,在不一樣軟件模塊中使用相同名稱的元素或屬性,可能會致使識別和衝突問題,而xml命名空間能夠解決該問題。code

結論

因此在svg中插入元素時,要使用document.createElementNS和setAttributeNS。即便使用setAttribute是生效的。xml

參考:
Document.createElementNS: What's the difference and why we need ithtm

相關文章
相關標籤/搜索