如何将Google.visualization.LineChart正确定位在div容器内
折线图溢出div容器修复方案
问题根源
图表溢出是4处代码问题共同导致的:
- 配置项拼写错误:图表
options里的高度属性误写为heigth,正确写法为height,你设置的高度规则完全没有生效,图表使用默认高度渲染,超出了grid容器设定的行高 - 冗余伪元素挤占空间:
.blocks的::before伪元素被设置为和容器等大的块级元素,直接把后续插入的图表挤到了容器外部 - 容器缺少溢出约束:
.blocks类没有设置溢出裁剪规则,超出边界的图表内容直接显示在容器外 - 重复加载资源:每次调用
draw函数都会重复执行google.charts.load,不仅浪费性能,还可能导致渲染时序错乱
修复步骤
- 修正图表配置的拼写错误,将高度设为100%适配父容器,同时增加
chartArea配置控制绘图区占比,给标题、坐标轴、图例预留足够空间 - 删除
.blocks::before的无用样式,避免挤占容器内部空间 - 给
.blocks类添加overflow: hidden、内边距和box-sizing: border-box规则,兜底裁剪溢出内容,同时避免内边距把容器撑大 - 将谷歌图表资源加载逻辑移到全局,仅加载一次,等DOM就绪后再批量生成容器、渲染图表
修正后完整代码
CSS部分
.containerGeral { display: grid; grid-template-columns: repeat(6, 540px); grid-auto-rows: 250px; grid-auto-flow: dense; grid-gap: 20px; padding: 10px; } .containerGeral .blocks { border-radius: 10px; background-color: #2E5173; overflow: hidden; padding: 8px; box-sizing: border-box; } .big { grid-column: span 3; }
HTML+JS部分
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="css/style.css"> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> </head> <body> <div id="test"></div> <div class="containerGeral"></div> <script> // 全局仅加载一次图表资源 google.charts.load('current', { 'packages': ['corechart'] }); function draw(id) { google.charts.setOnLoadCallback(function() { var options = { title: 'title', curveType: 'function', colors: ['#0409BA', '#00930A'], lineWidth: 3, vAxis: { viewWindow: { min: 0, max: 100 } }, legend: { position: 'bottom' }, top: 0, width: '100%', height: '100%', chartArea: {width: '90%', height: '70%'} }; var chart = new google.visualization.LineChart(document.getElementById(id)); var data = google.visualization.arrayToDataTable([ ['x', 'y'], [0, 0], [1, 1], [2, 3], [3, 7], [4, 15], [5, 31] ]); chart.draw(data, options); }); } // DOM加载完成后再生成元素渲染图表 $(function() { for (let i = 0; i < 16; i++) { if (i % 6 == 0 && i > 0) { $('<div class="big blocks" id="a' + i + '">titlee' + i + '</div>').appendTo('.containerGeral') $('<div class="big blocks" id="b' + i + '">titlee' + i + '</div>').appendTo('.containerGeral') continue } $('<div class="blocks" id="c' + i + '"></div>').appendTo('.containerGeral') draw('c' + i) } }) </script> </body> </html>
修改完成后,折线图会完全约束在.blocks容器内部,不会再出现溢出问题。
内容的提问来源于stack exchange,提问作者sysOut
相关产品推荐
相关产品推荐

