我在考虑如何用纯JavaScript(document.createElement)创建材料图标
const iconBox = document.createElement("div");
iconBox.style.width = "28px";
iconBox.style.cursor = "pointer";
iconBox.style.display = "flex";
iconBox.style.opacity = "1";
iconBox.style.position = "relative";
iconBox.style.alignItems = "center";
iconBox.style.justifyContent = "center";
iconBox.style.backgroundColor = "#ffffff";
const svg = document.createElement("svg");
svg.style.width = "1em";
svg.style.height = "1em";
svg.style.flexShrink = "inlineBlock";
svg.style.transition = "fill 200ms";
svg.style.flexShrink = "0";
svg.style.userSelect = "none";
svg.style.fontSize = "2.1875rem";
const path = document.createElement("path");
path.setAttribute(
"d",
"M14.59 8L12 10.59 9.41 8 8 9.41 10.59 12 8 14.59 9.41 16 12 13.41 14.59 16 16 14.59 13.41 12 16 9.41 14.59 8zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"
);
svg.appendChild(path);
iconBox.appendChild(svg);
const container = document.getElementById("container");
container!.appendChild(iconBox);
console.log(container, "container");但不知何故,在web浏览器中,图标没有显示出来( div、svg和path都在那里)
这是一个网页浏览器控制台的屏幕截图。

这是我的码箱,完整的代码在那里。
发布于 2021-08-22 14:39:15
因为svg元素是XML而不是HTML,所以需要使用适当的命名空间来创建元素。所以而不是
document.createElement("svg");和
document.createElement("path");你需要使用:
document.createElementNS("http://www.w3.org/2000/svg", "svg");和
document.createElementNS("http://www.w3.org/2000/svg", "path");
有关的答覆载有进一步的解释:
关于createElementNS的文档:
https://stackoverflow.com/questions/68879776
复制相似问题