html - 如何使用纯 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 path
are there)
这是 Web 浏览器控制台的屏幕截图。
这是我的代码框,整个代码都在那里。
解决方案
因为 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 的文档:
推荐阅读
- bash - 如何在 bash 中使用 read 仅将一个确定的字母分配给变量?
- ruby-on-rails - 在 Devise rails 中注册之前的条件
- rx-java - 在后台调度程序上订阅时不会调用 doOnDispose
- python - pypyodbc - 使用存储过程并将数据存储到数据框中
- for-loop - Tcl/tk:我应该使用 for 还是 foreach?
- jquery - 让所有表单字段同时验证,包括 recaptcha
- sql - 使用 SQL Server 中的查询在表中使用类似功能的复选框
- sql - RedShift 中更新语句中的表别名
- mysql - 如何仅选择具有非空值sql的列
- reactjs - 样式化组件渲染触发元素类型错误