使用JavaScript修改SVG后,如何让浏览器刷新显示?
问题
尝试通过JavaScript动态修改SVG,控制台显示DOM已正确添加新元素,但浏览器并未渲染这条新增的斜线。初始SVG显示一条红色斜线,目标是添加另一条斜线组成X形,已按要求使用SVG命名空间创建元素,但问题依然存在。
示例代码:
<div class="svg"> <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 40" style="background-color: #333;"> <line x1="10" x2="40" y1="40" y2="10" stroke="red"></line> </svg> </div> <script> const svg = document.getElementById('svg'); const svgNS = svg.getAttribute('xmlns'); const line = document.createElementNS(svgNS, 'line'); line.setAttributeNS(svgNS, 'x1', '10'); line.setAttributeNS(svgNS, 'x2', '40'); line.setAttributeNS(svgNS, 'y1', '10'); line.setAttributeNS(svgNS, 'y2', '40'); line.setAttributeNS(svgNS, 'stroke', 'red'); svg.appendChild(line); console.log(svg); </script>
解决方法
问题核心是错误地给SVG普通属性使用了setAttributeNS。SVG的常规属性(如x1、y1、stroke等)不属于任何命名空间,只有少数特殊属性(如XLink相关属性)才需要指定命名空间。
修正后的代码只需将setAttributeNS替换为普通的setAttribute:
<div class="svg"> <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 40" style="background-color: #333;"> <line x1="10" x2="40" y1="40" y2="10" stroke="red"></line> </svg> </div> <script> const svg = document.getElementById('svg'); const svgNS = svg.getAttribute('xmlns'); const line = document.createElementNS(svgNS, 'line'); // 改用setAttribute设置普通属性 line.setAttribute('x1', '10'); line.setAttribute('x2', '40'); line.setAttribute('y1', '10'); line.setAttribute('y2', '40'); line.setAttribute('stroke', 'red'); svg.appendChild(line); </script>
补充说明
创建SVG元素时必须使用createElementNS指定SVG命名空间,这一步是正确的。但设置属性时,只有像xlink:href这类带命名空间的属性才需要用setAttributeNS,其余基础属性直接用setAttribute即可。错误指定命名空间后,浏览器无法识别这些属性,导致元素无法正确渲染,尽管DOM结构看起来正常。
内容的提问来源于stack exchange,提问作者Erick Robertson
相关产品推荐
相关产品推荐

