我有一個帶有 SVG 格式圖示的 javascript 物件
const icons = {
// Icon for the "Add to cart" button
add: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove from cart" button
remove: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
removeAll: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
};
我想在 HTML 中使用它
<span>{icons.add}</span>
<span>{icons.remove}</span>
現在它顯示為字串并且未呈現圖示。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
現在是 2022 年,創建自己的Native Web Component 來撰寫
所有現代瀏覽器和所有框架都支持的<svg-icon>語意 HTML
<script>
customElements.define("svg-icon", class extends HTMLElement {
connectedCallback() {
this.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24">`
`<path d="` {
add: `M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z`,
remove: `M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z`,
removeAll: `M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z`,
}[ this.getAttribute("is") ]
`" fill="none"/></svg>`;
}
});
</script>
<svg-icon is="add"></svg-icon>
<svg-icon is="remove"></svg-icon>
<svg-icon is="removeAll"></svg-icon>
uj5u.com熱心網友回復:
您需要select將元素插入svg內部并用于innerHTML注入SVG內部。
const icons = {
// Icon for the "Add to cart" button
add: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove from cart" button
remove: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
removeAll: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
};
const addIcons = document.querySelectorAll('.add');
const removeIcons = document.querySelectorAll('.remove');
addIcons.forEach(span => span.innerHTML = icons.add)
removeIcons.forEach(span => span.innerHTML = icons.remove)
<span class="add"></span>
<span class="remove"></span>
uj5u.com熱心網友回復:
我用的是苗條的。它有@html 標簽。我可以簡單地使用 {@html icons.add}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516150.html
上一篇:PythonSelenium如何與網頁上的特定按鈕進行互動
下一篇:為什么應用程式加載時不請求svg
