使用Google Material Symbols替换Font Awesome图标时显示文本的问题
问题:Google Material Symbols Sharp样式图标仅单个显示正常
尝试用两款Sharp样式的Google Material Symbols替换Font Awesome图标,引入样式表后,delete图标正常显示,但shopping_basket图标仅显示文本,且该问题仅在同时使用两款Sharp图标时出现。
操作步骤
- 在页面
</head>标签前引入两款图标对应的样式表:- Sharp样式"delete"图标代码:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&icon_names=delete" /> <style> .material-symbols-sharp { font-variation-settings: 'FILL' 0, 'wght' 200, 'GRAD' 0, 'opsz' 20 } </style> - Sharp样式"shopping_basket"图标代码:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&icon_names=shopping_basket" /> <style> .material-symbols-sharp { font-variation-settings: 'FILL' 0, 'wght' 200, 'GRAD' 0, 'opsz' 24 } </style>
- Sharp样式"delete"图标代码:
- 在主题自定义JS字段添加图标替换代码:
- 替换"delete"图标:
document.querySelectorAll("i.fa.fa-trash-o").forEach(icon => { icon.replaceWith(Object.assign(document.createElement("span"), { className: "material-symbols-sharp", textContent: "delete" })); }); - 替换"shopping_basket"图标:
var cartIcon = $(".fa.fa-shopping-bag.fa-fw.icon"); cartIcon.parent().html("<span class='material-symbols-sharp'>shopping_basket</span>")
- 替换"delete"图标:
问题现象
delete图标正常显示,shopping_basket图标仅显示文本"shopping_basket"。
解决方案
问题根源在于两次重复引入Material Symbols Sharp字体样式表:后引入的样式会覆盖前一个的字体加载规则,且两次请求仅加载了各自指定的单个图标,导致其中一个图标对应的字符未被加载。
修复步骤:
- 合并字体请求:将两个图标的请求合并为一个
<link>标签,同时指定两个图标名称,避免重复加载和规则覆盖:<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&icon_names=delete,shopping_basket" /> - 统一并拆分样式设置:合并重复的基础样式,通过额外类给不同图标单独设置
opsz参数,避免样式冲突:<style> .material-symbols-sharp { font-variation-settings: 'FILL' 0, 'wght' 200, 'GRAD' 0; } /* 给delete图标单独设置尺寸 */ .material-symbols-sharp.delete-icon { font-variation-settings: 'FILL' 0, 'wght' 200, 'GRAD' 0, 'opsz' 20; } /* 给shopping_basket图标单独设置尺寸 */ .material-symbols-sharp.basket-icon { font-variation-settings: 'FILL' 0, 'wght' 200, 'GRAD' 0, 'opsz' 24; } </style> - 更新JS替换代码:给对应span添加专属类,应用单独的尺寸设置:
- 替换delete图标:
document.querySelectorAll("i.fa.fa-trash-o").forEach(icon => { icon.replaceWith(Object.assign(document.createElement("span"), { className: "material-symbols-sharp delete-icon", textContent: "delete" })); }); - 替换shopping_basket图标:
var cartIcon = $(".fa.fa-shopping-bag.fa-fw.icon"); cartIcon.parent().html("<span class='material-symbols-sharp basket-icon'>shopping_basket</span>")
- 替换delete图标:
调整后,两个图标对应的字体字符会被同时加载,且各自样式独立,均可正常显示。
内容的提问来源于stack exchange,提问作者ccristian
相关产品推荐
相关产品推荐

