我想使用能够通过 CSS 动态更改颜色和大小的图标。我决定使用 SVG 图标,灵感来自 CSS Tricks 在其网站上使用 SVG 图标的方式。
这是我的做法(类似于 CSS 技巧):
在我的页脚模板中,我添加了如下内容:
<footer>
<!-- Amazing footer -->
<!-- ... -->
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" display="none">
<symbol id="icon-search" viewBox="0 0 470 470">
<title>icon-search</title>
<path d="M447.05,428l-109.6-109.6c29.4-33.8,47.2-77.9,47.2-126.1C384.65,86.2,298.35,0,192.35,0C86.25,0,0.05,86.3,0.05,192.3 s86.3,192.3,192.3,192.3c48.2,0,92.3-17.8,126.1-47.2L428.05,447c2.6,2.6,6.1,4,9.5,4s6.9-1.3,9.5-4 C452.25,441.8,452.25,433.2,447.05,428z M26.95,192.3c0-91.2,74.2-165.3,165.3-165.3c91.2,0,165.3,74.2,165.3,165.3 s-74.1,165.4-165.3,165.4C101.15,357.7,26.95,283.5,26.95,192.3z"></path>
</symbol>
</svg>
</footer>
现在我可以在任何我想要的地方使用图标,如下所示:
<form>
<input type="text" name="q" placeholder="Search here...">
<button type="submit">
<svg class="icon-svg icon-search" width="22px" height="22px">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-search"></use>
</svg>
</button>
</form>
它可以工作...但是有时在页面加载时一些随机图标根本不会显示。到目前为止,这个问题是在 chrome 上出现的,例如在 firefox 中似乎没有。 知道是什么原因造成的吗?我的实现有什么问题吗?
谢谢。
最佳答案
我之前必须对此进行调试,丢失的图标总是会在重新加载后加载。它让我发现,如果页面加载有点停止并且图标位于页面末尾附近,<use xlink:href="...">
元素找不到它引用的符号。
将 SVG 图标放置在页面顶部附近可以解决此问题(在 <use>
的任何实例之前)。
关于html - 随机 SVG 图标无法加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44759748/