关于echart中使用width:100%与display:none中图表不能正常显示的问题

先查看需求

    要求类似于web端tab的样式,点击切换。因为是在移动端的应用,为了适配,宽度一般都采用%来表示,移动端宽度设置为100%
当echart对应的div采用display:none,
代码如下

<div id="container">
	<div id="map1"  style="width:100%;height:300px;"></div>
	<div id="map1_1" style="width:100%;height:300px;display:none"></div>
</div>
<div class="stationList" style="width: 100%;text-align: center;">
	<ul id="tab" style="width:45%;margin:0px auto">
		 <li id="tab1" class="selected" style="width:48%">上一页</li>
		 <li id="tab2" style="width:48%">下一页</li>
	</ul>
</div>
	var currentIndex = 0;
		var $contents = $('#container>div')
		$("#tab>li").click(function(){
			$contents[currentIndex].style.display ="none";
			var index =$(this).index();
			$contents[index].style.display = "block";
			$(this).addClass("selected").siblings().removeClass("selected");
			currentIndex = index
		})
		
		$("ul#nav li").on("click", function() {
			$(this).addClass("selected").siblings().removeClass("selected");
			//var id = $(this).attr("dataid");
			var id=$("ul#nav li.selected").attr('dataid');
			now=$('#monthDate').val();
			requestHourData(id,"",now);
		})
	function requestDayData(index,date) {
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "app/raindaystatistic_day.do",
			data: {index: index,date:date},
			contentType: "application/x-www-form-urlencoded",
			timeout: 30000,
			async: true,
			cache: true,
			success: function(varList) {
				var data = varList.result;
				var stationList = [];
				var stationList1 = [];
				var stationValue = [];
				var stationValue1 = [];
				var RainDayCount = 0;
				for (var i = 0; i < data.length; i ++) {
					var station_name =data[i].ss_station_name.replace("泵站","")
					if(i<data.length/2){
						stationList.push(station_name);
						stationValue.push(data[i].RainDay);
					}else{
						stationList1.push(station_name);
						stationValue1.push(data[i].RainDay);	
					}
				RainDayCount+=data[i].RainDay
				};
				var RainAvg = (RainDayCount/(data.length)).toFixed(1);
				var option = {
					    title: {
					        text: '泵站降雨量/mm ' + varList.pd.date,
		        	        left :'center',
					        textStyle: {
					            fontSize: 14,
					            fontWeight: 'bolder',
					            color: '#00A8E6'        // 主标题文字颜色
					        },
 				    },
					    tooltip: {
					        trigger: 'axis'
					    },
					    legend: {
					    	show:false,
					        data:['降雨量']
					    },
					    toolbox: {
					        show: false,
					        feature: {
					            dataZoom: {
					                yAxisIndex: 'none'
					            },
					            dataView: {readOnly: false},
					            magicType: {type: ['line', 'bar']},
					            restore: {},
					            saveAsImage: {}
					        }
					    },
					    xAxis:  {
					        type: 'category',
					        data: stationList,
					        axisLabel: {
					            interval:0, //强制显示文字					           
					    }
					    },
					    yAxis: {
					        type: 'value',
					        axisLabel: {
					            formatter: '{value}'
					        }
					    },
					    grid:{
			                   bottom:30
						    },
					    series: [
					        {
					            name:'降雨量',
					            type:'bar',
					            data:stationValue,
					            markPoint: {
					                data: [
					                    {type: 'max', name: '最大值'},
					                    {type: 'min', name: '最小值'}
					                ]
					            },
					            itemStyle: {
				                    normal: {
				                        color: function(params) {
				                            var colorList = [
				                              '#E80113','#EF7F01','#EEBB12','#E7FC427','#1CA2DF'
				                            ];
				                            return colorList[params.dataIndex]
				                        },
				                        label : {
	                                       show: true,
	                                       position: 'top'
	                                   }
				                    }
	                   					
				                },
					            barWidth: 20,
					            markLine: {
					                data: [
					                	 {
					                	        name: '平均值',
					                	        yAxis: RainAvg
					                	    }
					                ]
					            }
					        }
					    ]
					};
				var option1 = {
					    title: {
					        text: '泵站降雨量/mm ' + varList.pd.date,
		        	        left :'center',
					        textStyle: {
					            fontSize: 14,
					            fontWeight: 'bolder',
					            color: '#00A8E6'        // 主标题文字颜色
					        },
 				    },
					    tooltip: {
					        trigger: 'axis'
					    },
					    legend: {
					    	show:false,
					        data:['降雨量']
					    },
					    toolbox: {
					        show: false,
					        feature: {
					            dataZoom: {
					                yAxisIndex: 'none'
					            },
					            dataView: {readOnly: false},
					            magicType: {type: ['line', 'bar']},
					            restore: {},
					            saveAsImage: {}
					        }
					    },
					    xAxis:  {
					        type: 'category',
					        data: stationList1
					    },
					    grid:{
			                   bottom:30
						    },
					    yAxis: {
					        type: 'value',
					        axisLabel: {
					            formatter: '{value}'
					        }
					    },
					    series: [
					        {
					            name:'降雨量',
					            type:'bar',
					            data:stationValue1,
					            markPoint: {
					                data: [
					                    {type: 'max', name: '最大值'},
					                    {type: 'min', name: '最小值'}
					                ]
					            },
					            itemStyle: {
				                    normal: {
				                        color: function(params) {
				                            var colorList = [
				                              '#E80113','#EF7F01','#EEBB12','#E7FC427','#1CA2DF'
				                            ];
				                            return colorList[params.dataIndex]
				                        },
				                        label : {
	                                       show: true,
	                                       position: 'top'
	                                   }
				                    }
	                   					
				                },
					            barWidth: 20,
					            markLine: {
					                data: [
					                	 {
					                	        name: '平均值',
					                	        yAxis: RainAvg
					                	 }
					                ]
					            }
					        }
					    ]
					};
			    var myChart = echarts.init(document.getElementById('map1'));
		        var myChart1 = echarts.init(document.getElementById('map1_1'));
		        myChart.setOption(option);
		        myChart1.setOption(option1);
	        	/*窗口自适应,关键代码*/
		        $("ul li.selected").addClass("selected").siblings().removeClass("selected");
		        var id=$("ul li.selected").attr('dataid');
		        requestHourData(id,index,date);
			},
			error: function(data) {
			}
		})
	}

结果:
在这里插入图片描述
在网上找了许多的教程,具体介绍如下:
因为对应的div设置了display:none,(此处不能使用visible:hidden)。所以echart没有获取到div的宽和高导致初始化失败,这时候可以:1.明确指定div的style.width和style.height ,也就是采用px。2:在div显示后手动调用 echartsInstance.resize 调整尺寸。
对于:
对于方案1,因为是移动端适配,宽度一般都是用%表示,所以这里不采用。
对于方案2,尝试过,但是没有成功。
这里我采用我的方法吧!当然,因为在我这边是成功的,也不能保证一定能解决其他同学的问题。
思路:
既然是因为div采用display:none修饰,而且宽度只能设置为100%,那么我在option被渲染之前,给echart所在的div添加,宽和高。
当然这个宽和高是是从已经渲染出来的div中选择的,也就是依据移动端的屏幕的大小。

代码如下:

/*代码过多,前面的已经重复,已省略*/
$("#map1").css({"width":$("#map1").width(),"height":$("#map1").height()});  
$("#map1_1").css({"width":$("#map1_1").width(),"height":$("#map1_1").height()});
var myChart = echarts.init(document.getElementById('map1'));
var myChart1 = echarts.init(document.getElementById('map1_1'));
myChart.setOption(option);
myChart1.setOption(option1);

结果:
在这里插入图片描述
至此,两行代码。忙活了一上午,问题解决! 这是我的关于解决此问题的思路和方法,如果有不足之处,或者有更好的方法,欢迎其他同学指正。

猜你喜欢

转载自blog.csdn.net/zhou_shadow/article/details/91378887