首页 > 解决方案 > 如何使用纯 JavaScript 创建 Material Icon

问题描述

我正在考虑如何用纯 JavaScript( document.createElement)创建 Material Icon

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");

但不知何故,在网络浏览器中,图标不显示(The div, svg, and pathare there)

这是 Web 浏览器控制台的屏幕截图。

在此处输入图像描述

这是我的代码,整个代码都在那里。

标签: htmlsvgmaterial-ui

解决方案


因为 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 的文档:


推荐阅读