javascript - 如何使用innerHTML 在 javascript 中添加 svg html 树?

标签 javascript html svg innerhtml

<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g class="check-box">
    <path class="vector" d="M16 0C7.17725 0 0 7.17725 0 16C0 24.8228 7.17725 32 16 32C24.8228 32 32 24.8228 32 16C32 7.17725 24.8228 0 16 0Z" fill="#e8e8e8" />
    <path class="tick" d="M24.1094 12.6094L15.4426 21.2759C15.1826 21.5359 14.8413 21.6667 14.5 21.6667C14.1587 21.6667 13.8174 21.5359 13.5574 21.2759L9.22412 16.9426C8.70264 16.4214 8.70264 15.5786 9.22412 15.0574C9.74536 14.5359 10.5879 14.5359 11.1094 15.0574L14.5 18.448L22.2241 10.7241C22.7454 10.2026 23.5879 10.2026 24.1094 10.7241C24.6306 11.2454 24.6306 12.0879 24.1094 12.6094V12.6094Z" fill="#FAFAFA" />
  </g>
</svg>

我想在 javascript 中使用innerHTML 添加它。我不想使用 img 标签链接 svg,因为我想使用纯 css 对 svg 的部分进行动画处理。

最佳答案

类似这样的事情:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            background: white
        }
        /* This will color the icon to green */
        .cool-icon .vector { /* The class of the circle path */
            fill: green
        }
    </style>
</head>
<body>
    <h1>JS Icon Inserter</h1>
    <p>Next to this paragraph is the icon element with the "cool-icon" class.</p>
    <!-- Only put a class -->
    <i class="cool-icon"></i>
</body>
<script>
    // This JS will insert this icon into the "cool-icon"
    const icon = '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><g class="check-box"><path class="vector" d="M16 0C7.17725 0 0 7.17725 0 16C0 24.8228 7.17725 32 16 32C24.8228 32 32 24.8228 32 16C32 7.17725 24.8228 0 16 0Z" fill="#e8e8e8" /> <path class="tick" d="M24.1094 12.6094L15.4426 21.2759C15.1826 21.5359 14.8413 21.6667 14.5 21.6667C14.1587 21.6667 13.8174 21.5359 13.5574 21.2759L9.22412 16.9426C8.70264 16.4214 8.70264 15.5786 9.22412 15.0574C9.74536 14.5359 10.5879 14.5359 11.1094 15.0574L14.5 18.448L22.2241 10.7241C22.7454 10.2026 23.5879 10.2026 24.1094 10.7241C24.6306 11.2454 24.6306 12.0879 24.1094 12.6094V12.6094Z" fill="#FAFAFA" /></g></svg>'
    const iconElement = document.querySelector('.cool-icon')
    iconElement.innerHTML = icon
</script>
</html>

关于javascript - 如何使用innerHTML 在 javascript 中添加 svg html 树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61179592/

相关文章:

css - Safari SVG 图像蒙版不使用 CSS 调整大小

html - SVG 边框以特定宽度截断

javascript - 如何在 JS FETCH API 之外访问返回值

javascript - jplayer:从页面上的链接播放 mp3

javascript - 使用 JavaScript 模拟 Tab 按键

html - CSS - 媒体查询 - 元素未正确堆叠/ float

javascript - 显示来自输入标签的图像,无法检索 src 中的数据

来自内联 svgs 的 css 边框工件

javascript - CSS-JAVASCRIPT Object.style.display = 值不工作(旋转设备)

javascript - 用javascript调用外部网页(跨域)