如何用JavaScript让SVG矩形完全覆盖指定区域?
解决SVG矩形无法完全覆盖目标区域的问题
嘿,我帮你揪出问题所在啦!你看到的底部浅蓝条,其实是#graphicArea这个div的背景色露出来了,咱们一步步来搞定它~
问题原因分析
出现这个情况主要有两个小细节没注意到:
- SVG默认是inline-block元素,浏览器会给它预留一点基线对齐的空隙,导致
#graphicArea的高度比SVG的600px要高一点,底部的浅蓝背景就趁机露出来了。 - 你的
#graphicArea样式只设置了宽度,没明确设置高度,它的高度是靠内部SVG撑开的,但因为SVG的inline特性,撑开的高度会比SVG实际高度多那么一丢丢。
解决方案
下面两种方案任选其一就能解决问题,推荐一起用,兼容性更稳:
方案1:把SVG设为块级元素
在CSS里给SVG添加display: block,消除inline元素带来的底部间隙:
#graphic { display: block; }
方案2:给#graphicArea明确设置高度
修改#graphicArea的CSS,把高度也设为600px,让它和SVG的高度完全匹配:
#graphicArea { width: 1400px; height: 600px; /* 添加这行 */ background: #a7def2; }
额外小优化:统一使用变量
你代码里已经定义了width和height变量,建议把硬编码的数值换成变量,以后改尺寸只需要改一个地方就行:
// SVG属性 .attr("width", width) .attr("height", height) // 矩形初始位置 .attr("y", height) .attr("width", width) // 过渡后的尺寸 .attr("height", height)
修改后的完整代码
你可以直接复制下面的代码测试:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> #graphicArea { width: 1400px; height: 600px; background: #a7def2; } #graphic { display: block; } </style> </head> <body> <div id="outer-wrapper"> <div id="graphicArea"> </div> </div> <script src="https://d3js.org/d3.v5.min.js"></script> <script> var width = 1400; var height = 600; var graphic; var gocceAlSec = 7; graphic = d3.select("#graphicArea").append("svg") .attr("width", width) .attr("height", height) .attr("id", "graphic") .attr("overflow", "hidden"); var dataset = [0]; graphic.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", 0) .attr("y", height) .attr("width", width) .attr("height", 0) .style("fill", "blue") .transition() .duration(50000) .attr("height", height) .attr("y", 0); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Danny
相关产品推荐
相关产品推荐

