最近在bootstrap中使用echarts,本来在一个页面显示全部图表时是正常的。
后面使用tab标签页界面切换不同表格时碰到的一个echarts bug,tab切换时,默认页显示的图表没有委托,但echarts图表默认隐藏的时候,渲染的默认宽度是100px。
问题原因:tab标签导致图表元素设置了display:none 属性值。
例子
DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>echart图表title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js">script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js">script> <script src="https://fastly.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js">script> head> <body> <div class="row" style="padding: 50px;"> <ul id="myTab" class="nav nav-tabs"> <li class="active"><a href="#chart1" data-toggle="tab">图1a>li> <li><a href="#chart2" data-toggle="tab">图2a>li> ul> <div id="myTabContent" class="tab-content"> <div class="tab-pane fade in active" id="chart1"> <p>内容1 homep> <div class="row" style="border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 5px;margin: 5px;"> <div style="width: 100%;height: 340px; border-bottom: 1px solid rgba(0, 0, 0, 0.1);"> <div id="mychart_0" style="width: 100%;height: 300px;">div> div> div> div> <div class="tab-pane fade" id="chart2" style="display: block;"> <div class="row" style="border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 5px;margin: 5px;"> <div style="width: 100%;height: 340px; border-bottom: 1px solid rgba(0, 0, 0, 0.1);"> <div id="mychart_1" style="width: 100%;height: 300px;">div> div> div> div> div> div> <script type="text/javascript"> function create_chart(elemnet_id) { var dom = document.getElementById(elemnet_id); var myChart = echarts.init(dom, null, { renderer: 'canvas', useDirtyRect: false }); var option; option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line', smooth: true } ] }; if (option && typeof option === 'object') { myChart.setOption(option); } window.addEventListener('resize', myChart.resize); } create_chart('mychart_0') create_chart("mychart_1") script> body> html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
参考
Echarts图表宽度变成100px,让图表宽度随着父元素自动适应,Vue实时监听宽度的变化,这可能是史上最好的解决方案! - 腾讯云开发者社区-腾讯云 (tencent.com)