将SVG渲染为HTML元素

时间:2016-11-17 16:02:56

标签: javascript html svg

我在下面的var中有一个svg: -

var chatInProgressText = "<svg id='Layer_4' data-name='Layer 4' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'>\n    <defs><style>.cls-1{fill:#474747;}.cls-2{fill:#fff;}</style></defs>\n    <title>chat-live-icon</title>\n    <path class='cls-1' d='M15.08,0C6.76,0,0,5.17,0,11.51,0,17.14,5.42,22,12.65,22.88L11.77,27a1.16,1.16,0,0,0,.43,1,1.14,1.14,0,0,0,.71.24,1.3,1.3,0,0,0,.35,0l.1,0c1.86-.76,4.91-4.15,6.2-5.65,6.35-1.5,10.6-5.91,10.6-11C30.15,5.17,23.39,0,15.08,0Z'/><path class='cls-2' d='M19.08,20.85a1.44,1.44,0,0,0-.78.47,37.25,37.25,0,0,1-4.53,4.56L14.4,23a1.48,1.48,0,0,0-.24-1.18,1.5,1.5,0,0,0-1.05-.61c-6.48-.71-11.37-4.87-11.37-9.68,0-5.4,6-9.79,13.35-9.79s13.35,4.39,13.35,9.79C28.43,15.81,24.67,19.56,19.08,20.85Z'/><circle class='cls-1' cx='8.14' cy='11.79' r='2'/><circle class='cls-1' cx='15.14' cy='11.79' r='2'/><circle class='cls-1' cx='22.14' cy='11.79' r='2'/>\n</svg>"

如何使用JavaScript将其渲染为img标记和div。任何帮助将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

在你的html中创建一个div,为它设置一个id,获取由ID创建的元素,将子内容附加到新的div中。

var chatInProgressText = "<svg id='Layer_4' data-name='Layer 4' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'>\n    <defs><style>.cls-1{fill:#474747;}.cls-2{fill:#fff;}</style></defs>\n    <title>chat-live-icon</title>\n    <path class='cls-1' d='M15.08,0C6.76,0,0,5.17,0,11.51,0,17.14,5.42,22,12.65,22.88L11.77,27a1.16,1.16,0,0,0,.43,1,1.14,1.14,0,0,0,.71.24,1.3,1.3,0,0,0,.35,0l.1,0c1.86-.76,4.91-4.15,6.2-5.65,6.35-1.5,10.6-5.91,10.6-11C30.15,5.17,23.39,0,15.08,0Z'/><path class='cls-2' d='M19.08,20.85a1.44,1.44,0,0,0-.78.47,37.25,37.25,0,0,1-4.53,4.56L14.4,23a1.48,1.48,0,0,0-.24-1.18,1.5,1.5,0,0,0-1.05-.61c-6.48-.71-11.37-4.87-11.37-9.68,0-5.4,6-9.79,13.35-9.79s13.35,4.39,13.35,9.79C28.43,15.81,24.67,19.56,19.08,20.85Z'/><circle class='cls-1' cx='8.14' cy='11.79' r='2'/><circle class='cls-1' cx='15.14' cy='11.79' r='2'/><circle class='cls-1' cx='22.14' cy='11.79' r='2'/>\n</svg>";
var d1 = document.getElementById('svg');
d1.insertAdjacentHTML('beforeend', chatInProgressText);

https://jsfiddle.net/s6un2fpc/1/