前端爬坑记之C3.js与Bootsrap modal的小坑
今天我这个前端菜鸡在写代码的过程中,要把c3.js生成的图表在bootstrap模态框里展示,当用户点击按钮弹出内容为c3.js图表的modal。想来也很简单,思路大概是这样:
1.准备一个点击的按钮和一个bootstrap的modal:
<button type="button" class="btn btn-primary" id="staSubdBtn">
Submit
</button>
<!-- Chart模态框(Modal) -->
<div class="modal fade" id="chart" tabindex="-1" role="dialog" aria-labelledby="chartLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<!-- <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> -->
<!-- </button> -->
<h4 class="modal-title" id="chartLabel">
<span class="icon mr-3"><i class="fa fa-line-chart"></i></span>Chart
</h4>
</div>
<div class="modal-body">
<div id="chart-pie" style="height: 16rem;max-width: 100%;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
2.弹出Modal,然后渲染图表(之前甚至想先在modal中渲染图表再显示——这样其实很愚蠢)
$("#staSubdBtn").on("click", function () {
$('#chart').modal('show');
var chart = c3.generate({
bindto: '#chart-pie',
data: {
columns: [
['data1', 63],
['data2', 44],
['data3', 12],
['data4', 14]
],
type: 'pie',
colors: {
'data1': tabler.colors["blue-darker"],
'data2': tabler.colors["blue"],
'data3': tabler.colors["blue-light"],
'data4': tabler.colors["blue-lighter"]
},
names: {
'data1': 'A',
'data2': 'B',
'data3': 'C',
'data4': 'D'
}
},
axis: {
},
legend: {
show: false,
},
padding: {
bottom: 0,
top: 0
},
});//end chart
});
此时,可能认为已经大功告成~NO NO NO,打开后如图:

检查了一下元素,发现渲染后的svg的width是页面的宽度。想了想原因在于,在点击了按钮调用modal之后立刻执行C3图表的渲染,此时modal还没有宽度,因此,渲染出来的svg的宽度是默认的页面的宽度。
那么,解决的方法就在modal本身。因为Bootstrap的modal不是一个单纯的css控件,需要jQuery的支持,本身也支持一些事件,其中有一个就是shown.bs.modal,这个事件在模态框对用户可见时触发,也就是在 CSS 过渡效果完成后触发。在此时modal就有对应的width,我们再来渲染图表就有了width了。因此把图表渲染部分放入 shown.bs.modal 事件中,问题就得到了解决。
$('#chart').on('shown.bs.modal', function () {
var chart = c3.generate({
bindto: '#chart-pie',
data: {
columns: [
['data1', 63],
['data2', 44],
['data3', 12],
['data4', 14]
],
type: 'pie',
colors: {
'data1': tabler.colors["blue-darker"],
'data2': tabler.colors["blue"],
'data3': tabler.colors["blue-light"],
'data4': tabler.colors["blue-lighter"]
},
names: {
'data1': 'A',
'data2': 'B',
'data3': 'C',
'data4': 'D'
}
},
axis: {
},
legend: {
show: false,
},
padding: {
bottom: 0,
top: 0
},
});//end chart
})
再回到浏览器查看,就正常了。

Echarts也是这个道理。
记录下
喜欢这篇文章的话可以扫描下方二维码支持我

版权声明:
作者:Kiwi
链接:https://www.qingwei.tech/programe-develops/1252.html
来源:清渭技术小站
文章版权归作者所有,未经允许请勿转载。
Somad
get it thank you but i am not good at Chinese and i need translation 🙂
Kiwi@Somad
Please Google it
Bigger
年后第一次来,恭喜恭喜!
hail
Hello There! Have A Good Day!