html - 带有 USE 标签的 SVG 不渲染

标签 html google-chrome internet-explorer svg

DOM 已经包含一个空的 SVG 标签 (svg)。当我尝试使用 id (iconId) 动态附加现有 SVG 符号 (symbol) 的 USE 标签时:

svg.empty();
svg[0].setAttribute('viewBox', symbol.getAttribute('viewBox'));
svg.append('<use xlink:href="#' + iconId + '"></use>');

它不再渲染 SVG。在 Chrome 中,如果我添加:

 element.html(element.html());

或手动操作 viewBox 属性,但这不是真正的解决方案,IE 根本不喜欢它。 值得一提的是,如果我直接附加 SVG 图形,元素就会呈现。

这里发生了什么,为什么在附加 USE 标签后没有绘制 SVG?

最佳答案

毕竟这确实是命名空间的问题。

具体来说,必须使用 document.createElementNSnode.setAttributeNS 创建和设置 SVG 元素和属性。

$(document).ready(function(evt) { 
  var svgns = 'http://www.w3.org/2000/svg',
      xlinkns = 'http://www.w3.org/1999/xlink',
      use = document.createElementNS(svgns, 'use');
  
  use.setAttributeNS(xlinkns, 'xlink:href', '#save');
  document.getElementById('useSVG').appendChild(use);
});
#svgStore { 
  display: none;  
}

#useSVG {
  width: 16px;
  height: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<svg style="display:none;" id="svgStore" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <symbol viewBox="0 0 16 16" id="save"><title>save</title>       <g id="svgstore3748a955346b4a088bbdc55a22f56504_x31_6_13_"> 
        <path style="fill-rule:evenodd;clip-rule:evenodd;" d="M9,4h2V2H9V4z M13,13H3v1h10V13z M13,11H3v1h10V11z M13,0H0v16h16V3L13,0z
		 M3,1h9v4H3V1z M14,15H2V8h12V15z M13,9H3v1h10V9z">
		   
		 </path> 
      </g> 
    </symbol>
</svg>
SVG use:
<svg id="useSVG" xmlns="http://www.w3.org/2000/svg"></svg>

感谢@RobertLongson 和 http://www.kevlindev.com/tutorials/basics/shapes/js_dom/用于指向答案。

关于html - 带有 USE 标签的 SVG 不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25975523/

相关文章:

google-chrome - Chrome 图像 EXIF 方向问题

javascript - 脚本 438 : Object doesn't support property or method 'join'

javascript - IntelliJ 可以在 Internet Explorer 中运行客户端 JavaScript 代码吗?

html - 网站 foobared 中等浏览器大小及以下 (zurb foundation)

javascript - 将一个 div 堆叠在隐藏在滚动条上的 Bootstrap 导航栏之上

javascript - HTML4 中的 Element.animate()

javascript - 在 IE 8+ 中运行时检测 IE 7 Emulate

php - 出现 "You have an error in your SQL syntax"错误 - PHP、MySQL

html - Internet Explorer 中的列表类型问题

html - 在 chrome 浏览器中将 svg 图像调整为背景