這兩天真的被這個問題抓狂,找了好多都沒有效果,百試無用。
不過有句話說的很對:方法總比問題多。遇到問題總會有解決方法,只要你願意試。
下面說下我的方法,其實很簡單
沒改前時這樣的,canvas超出父級div的寬度
改之后
話不多說,上代碼
// 圖表 var myChart = echarts.init(document.getElementById('sale-chart')); var legend=""; // 指定圖表的配置項和數據 var option = { //圖表配置標題 title: { text: '銷量(萬輛)', textStyle: { fontSize: 12, fontWeight: 400, color: '#000000' }, left: 5 }, color:'#0E76E4', //配置提示信息 tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: { show: true, right: '10%', top: 2, itemWidth: 10, itemHeight: 4, textStyle: { color: '#1a1a1a', fontSize: 12, icon: 'rect', }, data:legend }, //設置中間內容距離div的距離,也就是內邊距 grid: { top: 35, left: 55, right: 45, width:'auto', height:'auto' }, dataZoom: [{ type: 'inside' }, { type: 'slider' }], // ], //x軸 xAxis: { name: '時間', // 給X軸加單位 nameLocation: 'end', type: 'category', //x軸文字配置 axisLabel: { show: true, inside: false, align: 'left', margin: 2, textStyle: { color: '#1a1a1a', fontSize: '10' } }, axisTick: { show: false }, //去掉x軸刻度線 // data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月"], data: [], axisLine: { show: false, length: 3, } }, //y軸 yAxis: { axisLabel: { show: true, textStyle: { color: '#1a1a1a', fontSize: '10' } }, axisLine: { show: false //y軸刻度線不顯示 } }, series: [{ // name: "", type: 'line', //圖表類型 // data: [266, 200, 306, 100, 100, 280, 500, 500], data: [], symbol: 'none', }] }; // 使用剛指定的配置項和數據顯示圖表。 --> myChart.setOption(option); //請求圖表數據 function chartData(){ $.ajax({ type: "get", url: "”, dataType: "jsonp", success: function (json) { console.log(json); // 需要倒序數組 myChart.setOption({ xAxis: { data: monthData.reverse() }, series: { data: saleData.reverse() }, legend: { data: legend }, }); //最關鍵,自動調整canvas的 myChart.resize(); }, error: function () { console.log("請求失敗"); } }) }
放了這么多代碼,其他配置好就兩句話
調用時加上 myChart.resize();
設置內邊距 grid
還有就是給父級的div寬度設置100%;

問題就解決了