You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Javascript动态创建的SVG use标签不生效,引用图形不显示如何解决?

问题原因
  • <use> 属于SVG元素,不能用普通的document.createElement()创建,必须和<svg>标签一样使用SVG命名空间创建
  • SVG的<use>标签引用资源的href属性,动态设置时需要使用http://www.w3.org/1999/xlink命名空间,部分浏览器不识别直接设置的无命名空间href属性
  • viewBox属性是属于外层<svg>容器的,设置在<use>标签上无效,会导致图形无法适配容器尺寸
修复方案

仅需修改JS代码即可,HTML、CSS无需调整,修复后的代码如下:

function test(){
 setTimeout(()=>{
    // 外层svg创建逻辑保留
    const a = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    a.classList.add("newbee");
    // 给外层svg添加viewBox,不要设置在use标签上
    a.setAttribute("viewBox","0 0 62.4 38.4");

    // 用SVG命名空间创建use标签
    const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
    // 兼容设置普通href和xlink命名空间的href
    use.setAttribute("href","#theBee");
    use.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#theBee");
    use.setAttribute("class","corr-p-3 bee");
    use.setAttribute("width","62.4");
    use.setAttribute("height","38.4");
    use.setAttribute("x","0");
    use.setAttribute("y","0");

    a.appendChild(use);
    document.body.appendChild(a);
    
    test();
 }, Math.floor(Math.random() * (6000 - 3000 + 1) ) + 3000)
}

test()

内容的提问来源于stack exchange,提问作者Shayan Kanwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 21:15:04