考慮這個簡單的頁面:
<html>
<body>
<svg width="250" height="250">
<g>
<path id="foo" d="M20,230 Q40,205 50,230 T90,230" stroke="red" stroke-width="3" fill="none" onclick="setBlue()" />
</g>
</svg>
<script>
function setBlue() {
document.getElementById("foo").setAttribute("stroke", "blue");
}
</script>
</body>
</html>
它將顯示一條紅色波浪線。如果您單擊該行,它將變為藍色。這表明 JavaScript 功能在此 SVG 物件中起作用,并且路徑元素foo已添加到 DOM 本身。
現在改為加載瀏覽器可以快取的靜態 SVG:
<img width="250" height="250" src="images/somesvg.svg" />
嵌入的 JavaScript 沒有命中。foo通過 JavaScript 或 jQuery請求 DOM不會回傳任何內容。
這是否意味著在 SVG 中命名元素或添加 JavaScript 功能的唯一方法是通過在 HTML 本身內部呈現 SVG?如果我可以將 ID 添加到 SVG 檔案中的路徑然后訪問它們,我可以顯著縮短頁面。
uj5u.com熱心網友回復:
如果是外部*.svg檔案,原生 Web Component<load-file>可以獲取它并注入到 DOM 中;無論是在 shadowDOM 中還是替換<load-file>Element,從而成為 DOM 的一部分,您可以使用 CSS 訪問和設定樣式。
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as async so await can be used
async connectedCallback(
// call connectedCallback with parameter to *replace* SVG (of <load-file> persists)
src = this.getAttribute("src"),
// attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(src)).text()
// append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute
// then replace <load-svg> with loaded content <load-svg>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
Dev.To post中的完整解釋:〈load-file〉Web Component,向DOM添加外部內容
uj5u.com熱心網友回復:
正如@diopside 和@RobertLongson 在評論中提到的,這里以不同的方式提出了這個問題:我對 SVG 檔案使用 <img>、<object> 或 <embed> 嗎?
解決方案是在其中使用<object>和嵌入 SVG。現在我可以與它互動,但瀏覽器不需要在每次加載頁面時重新加載影像。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346167.html
