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

纯JavaScript创建SVG:用href替代已废弃的xlink:href

问题:动态设置SVG <use>元素的href属性时,setAttributeNS的命名空间参数应填写什么?

我有一个包含所有图标的SVG精灵图,之前动态添加图标时用的是这段JavaScript代码:

let closeButton = document.createElementNS("http://www.w3.org/2000/svg", "svg");
let svgUse = document.createElementNS('http://www.w3.org/2000/svg', 'use');
svgUse.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'css/sprite.svg#warning');
closeButton.append(svgUse);

这段代码能正常运行,但MDN文档指出xlink:href已废弃:

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

为了适配未来标准,我想动态设置use元素的href属性,但无法直接使用setAttribute方法,请问setAttributeNS的命名空间参数应该填什么?

svgImg.setAttributeNS('what to put here?', 'href', 'css/sprite.svg#warning');

我没找到相关文档说明。


解答

现代SVG标准中的href属性属于无命名空间属性,不需要通过setAttributeNS来设置,直接使用普通的setAttribute方法即可:

let closeButton = document.createElementNS("http://www.w3.org/2000/svg", "svg");
let svgUse = document.createElementNS('http://www.w3.org/2000/svg', 'use');
// 直接用setAttribute设置href,无需命名空间
svgUse.setAttribute('href', 'css/sprite.svg#warning');
closeButton.append(svgUse);

如果一定要使用setAttributeNS(比如特殊场景需求),命名空间参数传入null或者空字符串''即可,因为该属性不属于任何命名空间:

svgUse.setAttributeNS(null, 'href', 'css/sprite.svg#warning');
// 或者
svgUse.setAttributeNS('', 'href', 'css/sprite.svg#warning');

之前的xlink:href需要指定命名空间,是因为它属于XLink命名空间;而新的href已经整合进SVG核心规范,不再依赖XLink命名空间,因此无需额外指定命名空间参数。


内容的提问来源于stack exchange,提问作者just some guy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:05:20