删除显示无改变图表的高度和宽度

时间:2019-05-23 14:03:26

标签: javascript html css

我正在编写一个使用Google图表生成图表的代码。这是原始代码。

      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
       <div id="piechart" style="width: 900px; height: 500px;"></div>
   

这是我的修改。最初,我不希望饼图显示。当我单击该按钮时,它应该出现。

google.charts.load('current', {
  'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 11],
    ['Eat', 2],
    ['Commute', 2],
    ['Watch TV', 2],
    ['Sleep', 7]
  ]);

  var options = {
    title: 'My Daily Activities',
    pieSliceText: 'value',

  };

  var chart = new google.visualization.PieChart(document.getElementById('piechart'));

  chart.draw(data, options);
}

function showPie() {
  document.getElementById("piechart").style.display = '';
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="piechart" style="width: 900px; height: 500px; display:none"></div>
<button type="button" onclick="showPie()">Click Me!</button>

即使这很好用,但我的问题是,为什么尺寸减小了?有没有办法即使我收回pieChart时也可以保留尺寸。请让我知道我要去哪里哪里以及如何解决它。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用display:none代替visibility:hidden,因为它仍然会渲染div,但不会渲染内容:

What is the difference between visibility:hidden and display:none?

答案 1 :(得分:0)

杀死div上的大小尺寸,然后将它们放置在options变量中,如下例所示,您应该一切顺利。

这是我以前遇到过的可视化库的怪癖之一。

google.charts.load('current', {
  'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 11],
    ['Eat', 2],
    ['Commute', 2],
    ['Watch TV', 2],
    ['Sleep', 7]
  ]);

  var options = {
    title: 'My Daily Activities',
    pieSliceText: 'value',
    width: 900,
  height: 500,

  };

  var chart = new google.visualization.PieChart(document.getElementById('piechart'));

  chart.draw(data, options);
}

function showPie() {
  document.getElementById("piechart").style.display = "";
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button type="button" onclick="showPie()">Click Me!</button>
<div id="piechart" style=" display:none;"></div>