为何无法通过JavaScript修改SVG元素的填充颜色?
SVG填充不生效的问题解决
问题根源
你遇到的问题有两个核心错误:
- CSS语法错误:SVG内部样式里的
fill="none';写法完全错误,CSS属性必须遵循属性名: 值;的格式,这个错误直接导致cal23的样式不生效,而SVG矩形默认填充色为黑色,所以cal23显示黑色。 - JavaScript属性误用:SVG元素的填充属性是
fill,而非HTML元素的backgroundColor,所以你的JS代码无法修改填充色。
修正方案
- 修复SVG内联样式
把SVG里的错误样式:
#cal23 { fill="none'; }
改成标准CSS格式:
#cal23 { fill: none; }
- 修正JavaScript代码
将style.backgroundColor替换为style.fill,或者使用setAttribute方法修改fill属性:
// 方法1:使用style.fill document.getElementById('cal23').style.fill = "red"; document.getElementById('cal24').style.fill = "red"; // 方法2:使用setAttribute // document.getElementById('cal23').setAttribute('fill', 'red'); // document.getElementById('cal24').setAttribute('fill', 'red'); console.log('Ran setColor on cal23 and cal24');
完整修正后的代码
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20.2 11"> <style> #cal23 { fill: none; } </style> <rect id="cal23" width="10" height="10" x="0" y="0" stroke-width="0.2" stroke="orange"/> <text x="5" y="5" font-size="1.5" text-anchor="middle" fill="black">Test</text> <rect id="cal24" width="10" height="10" x="10" y="0" stroke-width="0.2" stroke="pink" fill="none"/> <text x="15" y="5" font-size="1.5" text-anchor="middle">Test</text> </svg> <style> body { background-color: yellow; } </style> <script> document.getElementById('cal23').style.fill = "red"; document.getElementById('cal24').style.fill = "red"; console.log('Ran setColor on cal23 and cal24'); </script>
内容的提问来源于stack exchange,提问作者Ed S.
相关产品推荐
相关产品推荐

