你是不是也曾经从网上下载了一个神秘的 svg.js 文件,却发现图标怎么都显示不出来?别担心,这里有一个简单而有趣的解决方案,让你轻松搞定!


下面是一个完整的 HTML 文件代码,只需要将 index.htmlsvg.js 放在同一个文件夹下,就能看到你心心念念的图标啦!

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
<!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>SVG Icon Display</title>    <style>        #icon-container {            display: none; /* 隐藏原始 SVG 字符串 */       }        #icon-display {            display: flex;            flex-wrap: wrap;            gap: 20px;       }        .icon {            width: 50px;            height: 50px;            fill: currentColor; /* 这将使图标颜色与当前文本颜色一致 */       }        .icon + div {            text-align: center;            font-size: 14px;       }    </style> </head> <body>    <div id="icon-container"></div>    <div id="icon-display"></div>    <script src="./svg.js"></script>    <script>        document.getElementById('icon-container').innerHTML =window._iconfont_svg_string_4562126; ​        const symbols = document.querySelectorAll('#icon-container symbol');        const iconDisplay = document.getElementById('icon-display'); ​        symbols.forEach(symbol => {            const iconId = symbol.id;            const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');            svg.setAttribute('class', 'icon');            svg.setAttribute('aria-hidden', 'true');            svg.innerHTML = `<use xlink:href="#${iconId}"></use>`;            const label = document.createElement('div');            label.textContent = `#${iconId}`;            const container = document.createElement('div');            container.appendChild(svg);            container.appendChild(label);            iconDisplay.appendChild(container);       });    </script> </body> </html>

小贴士

  1. 确保文件在同一个文件夹:将 index.htmlsvg.js 文件放在同一个文件夹下,这样才能正确加载图标。

  2. 命名一致:确保 svg.js 文件中的变量名为 window._iconfont_svg_string,这样代码才能正常工作。

结语

通过以上简单的步骤,你就可以在网页中展示从互联网下载的 svg.js 文件中的图标了。再也不用抓狂于那些显示不出来的图标了,赶紧试试吧!