javascript - 如何使用 vanilla javascript 动态添加 SVG 图标
问题描述
我将如何使用 vanilla javascript 添加 SVG 图标?在 HTML 中你只要把它放进去,就是这样。在 javascript 上,我尝试了很多东西,但都没有奏效。我需要根据用户操作动态添加一堆。
这是它在 HTML 中的实现方式:
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-settings" width="16" height="16" viewBox="0 0 24 24" stroke-width="1.5" stroke="#9E9E9E" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
<path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z" />
<circle cx="12" cy="12" r="3" />
</svg>
将上述内容放在 HTML 中的任何位置都会导致“设置”图标出现在该位置。
解决方案
这很简单,而且只有一条线:
const svgIcon = `<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-settings" width="16" height="16" viewBox="0 0 24 24" stroke-width="1.5" stroke="#9E9E9E" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065z" /><circle cx="12" cy="12" r="3" /></svg>`;
document.getElementById('targetElement').outerHTML += svgIcon;
<div id="targetElement"></div>
推荐阅读
- python - 用不同的签名覆盖父类方法是一种好习惯吗?
- reactjs - React 组件如何通过路由调用参数?
- python-3.x - TensorFlow 运行时 PyCharm 崩溃
- firebase - 在控制台中显示错误消息而不是抛出异常(Flutter Firebase)
- flutter - flutter DropDownButtonFormField 提示抛出运行时错误
- c# - EF Core 中的零或一关系
- python - 无法将字节从 Python serial.write() 发送到 Arduino
- django - inlineformset_factory:验证失败(此字段为必填项)
- r - 将 JSON 排序到数据框的映射函数(带有嵌套列表)
- python - 使用 python 创建 Mysql 数据库 - 不断收到 1064 错误(...在 '%s' 附近使用正确的语法)