使用fonticon时 直接<svg class=”icon” aria-hidden=”true”> <use xlink:href=”#icon-xxx”></use> </svg>可以显示图片
js动态添加svg标签无法显示图片
两个问题:
1.svg基于xml 在html中使用需要指明namespace
2.查阅mdn文档(
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
)发现SVG 2 removed the need for the
xlink
namespace, so instead of
xlink:href
you should use
href
.
// 创建svg use需要指明命名空间
let icon = document.createElementNS(
"http://www.w3.org/2000/svg",
"svg"
);
icon.setAttribute("xmlns", "http://www.w3.org/2000/svg");
icon.setAttribute("class", "icon");
icon.setAttribute("aria-hidden", "true");
icon.setAttribute("fill", "currentColor");
//use元素
let use = document.createElementNS(
"http://www.w3.org/2000/svg",
"use"
);
// xlink:href替换为href成功显示图标
use.setAttribute("href", "#icon-xxx");
icon.appendChild(use);
版权声明:本文为ZY_201803原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。