【问题标题】:Google Bar chart is not taking full width while in bootstrap accordion谷歌条形图在引导手风琴中没有占据全宽
【发布时间】:2017-04-20 18:29:19
【问题描述】:

Google 图表在 bootstrap 手风琴中未占据全宽

我知道@asgallant 之前已经回答了这个问题的一个版本。但是,我无法使该答案适应这里的工作。

我需要帮助 1/ 让第二个手风琴显示图表的全宽 - 还没有找到工作解决方案 和 2/ 如何根据值用不同的颜色给条上色。我知道这已经发布过,但没有使用谷歌表格作为数据源。

提前致谢 哈特穆特

网页在这里 https://www.hartgoods.com/main/my-symptom-tracker/barchart-accordian.html

代码在这里

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Collapse</h2>
  <p><strong>Note:</strong> The <strong>data-parent</strong> attribute makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.</p>
  <div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
        </h4>
      </div>
      <div id="collapse1" class="panel-collapse collapse in ">
        <div class="panel-body">
        
        
        
        
        Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        
        <br> <br>
        
        <!--START CHART -->
<!--First Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Only load the above ONCE per page-->
<script type="text/javascript">
// Load the Visualization API and the corechart package.
//include extra packages that or not included in the corechart package  
// corechart package includes (bar, column, line, area, stepped area, bubble, pie, donut, combo, candlestick, histogram, scatter)
google.charts.load('current', {packages: ['corechart', 'annotationchart', 'table']});
// Set a callback to run when the Google Visualization API is loaded
google.charts.setOnLoadCallback(drawChart);

/*
The syntax of the query language is composed of the following clauses. 
The order of the clauses must be as follows:

select		Selects which columns to return, and in what order. If omitted, all of the table's columns are returned, in their default order.
where		Returns only rows that match a condition. If omitted, all rows are returned.
group by	Aggregates values across rows.
pivot		Transforms distinct values in columns into new columns.
order by	Sorts rows by values in columns.
limit		Limits the number of returned rows.
offset		Skips a given number of first rows.
label		Sets column labels.
format		Formats the values in certain columns using given formatting patterns.
*/
  
/*send the query - using the "sheet" parametre not the GID parameter

The query supports the following optional parameters:
headers=N: Specifies how many rows are header rows, where N is an integer zero or greater. 
These will be excluded from the data and assigned as column labels in the data table. 
If you don't specify this parameter, the spreadsheet will guess how many rows are header rows. 
Note that if all your columns are string data, the spreadsheet might have difficulty determining which rows are header rows without this parameter

gid=N: Specifies which sheet in a multi-sheet document to link to, if you are not linking to the first sheet. N is the sheet's ID number. 
You can learn the ID number by navigating to the published version of that sheet and looking for the gid=N parameter in the URL. 
You can also use the sheet parameter instead of this parameter. Gotcha: Google Spreadsheets might rearrange the gid parameter in the URL when viewed in a browser; 
if copying from a browser, be sure that all parameters are before the URL's # mark. Example: gid=1545912003.

sheet=sheet_name: Specifies which sheet in a multi-sheet document you are linking to, if you are not linking to the first sheet. 
sheet_name is the display name of the sheet. Example: sheet=Sheet5.
*/
  
//send the query - using the "sheet" parametre - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
function drawChart() {
  var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/13ZXjNfFOf0glEzEkAg5VWXNTP3oZPaDR9WKwa0kTrds/gviz/tq?sheet=Sheet2&headers=1&tq=SELECT A, B   where B > 0 and B <= 5 ORDER BY B desc  limit 1000 offset 0');
 query.send(handleSampleDataQueryResponse);
}

//draw the chart -  - using the "sheet" parametre - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
    function handleSampleDataQueryResponse(response){
// ADD some error handling - START
 if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
      }
// ADD some error handling - END

//get data table
var data = response.getDataTable();


//adjust chart and bar height according to how many rows
 var chartAreaHeight = data.getNumberOfRows() * 30;
  var chartHeight = chartAreaHeight + 400;
  
  
  
  // Set chart options - START
   var options = {
//set transparency of the chart background, whether the chart is stacked and importantly, 
//the physical height, in pixels of the chart.
    backgroundColor: 'transparent',
    isStacked: false,
     height: chartHeight,
  

 // control colours of lines NOTE this overides automatic colouring
           colors: ['orange', 'magenta',"blue"],
           //control opacity of bars
            dataOpacity:.85,
            
chartArea: {
      height: chartAreaHeight,
      top: "100",
      right: "100",
      bottom: "100",
      left: "100"
    },
/*An object with members to configure the placement and size of the chart area (where the chart itself is drawn, 
excluding axis and legends). Two formats are supported: a number, or a number followed by %. 
A simple number is a value in pixels; a number followed by % is a percentage.*/
  
  
  
  animation:{startup:'true',duration:'3000',easing:'inAndOut'},
  //makes the chart transparent so the background color shows through
 
      // chart title
          title:'MSQ Results', 
        titleTextStyle: {color: 'white',fontSize:30,fontName: 'arial',bold: false,italic: false},
       // control position of legend
          legend: { position: 'top',textStyle: {color: 'orange', fontSize: 24}},
          
           // horizontal axis title and formating
        vAxis: {
          textPosition:'in',
          title: 'SYMPTOMS',
          titleTextStyle: {color: 'white',fontSize: 24,fontName: 'Arial',bold: false,italic: false},
            textStyle: {color: 'black',fontSize: 13,fontName: 'Arial',bold: false,italic: false},
        gridlines: {color: 'white', count: 5,  units:''},
        minorGridlines: {color: 'green', count:0 ,  units:''}   },
         
          // horizontal axis title and formating
        hAxis: {
        baseline:0,
        baselineColor:'white',
        title: 'SCORE',
           titleTextStyle: {color: 'white',fontSize: 24,fontName: 'Arial',bold: false,italic: false},
                textStyle: {color: 'white',fontSize: 18,fontName: 'Arial',bold: false,italic: false},
            minValue:0, maxValue:4,
            gridlines: {color: 'white', count: 5,  units:''},
            minorGridlines: {color: 'green', count:0 ,  units:''}  },
    
     };
   // Set chart options - END
   
   
  
//draw the chart
var chart = new google.visualization.BarChart(document.getElementById('mychart'));


    
chart.draw(data,options );

  
   
 
     
   
    
      window.addEventListener('resize', function () {
    chart.draw(data, options);
  }, false);
    


}
  
</script>
      
<div style="font-family:opensans;border: 0 none; background-color:#009688;">       
     <!-- div to show the chart on the web page --> 
    <div id="mychart" ></div>  
    </div>
    
<!--END CHART -->  

 
        
        
        
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
        </h4>
      </div>
      <div id="collapse2" class="panel-collapse collapse">
        <div class="panel-body">
        
        
   Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
        
        
        
        
        
      <br> <br> Chart 2






 <!--START CHART -->
<!--First Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Only load the above ONCE per page-->
<script type="text/javascript">
// Load the Visualization API and the corechart package.
//include extra packages that or not included in the corechart package  
// corechart package includes (bar, column, line, area, stepped area, bubble, pie, donut, combo, candlestick, histogram, scatter)
google.charts.load('current', {packages: ['corechart', 'annotationchart', 'table']});
// Set a callback to run when the Google Visualization API is loaded
google.charts.setOnLoadCallback(drawChart);

/*
The syntax of the query language is composed of the following clauses. 
The order of the clauses must be as follows:

select		Selects which columns to return, and in what order. If omitted, all of the table's columns are returned, in their default order.
where		Returns only rows that match a condition. If omitted, all rows are returned.
group by	Aggregates values across rows.
pivot		Transforms distinct values in columns into new columns.
order by	Sorts rows by values in columns.
limit		Limits the number of returned rows.
offset		Skips a given number of first rows.
label		Sets column labels.
format		Formats the values in certain columns using given formatting patterns.
*/
  
/*send the query - using the "sheet" parametre not the GID parameter

The query supports the following optional parameters:
headers=N: Specifies how many rows are header rows, where N is an integer zero or greater. 
These will be excluded from the data and assigned as column labels in the data table. 
If you don't specify this parameter, the spreadsheet will guess how many rows are header rows. 
Note that if all your columns are string data, the spreadsheet might have difficulty determining which rows are header rows without this parameter

gid=N: Specifies which sheet in a multi-sheet document to link to, if you are not linking to the first sheet. N is the sheet's ID number. 
You can learn the ID number by navigating to the published version of that sheet and looking for the gid=N parameter in the URL. 
You can also use the sheet parameter instead of this parameter. Gotcha: Google Spreadsheets might rearrange the gid parameter in the URL when viewed in a browser; 
if copying from a browser, be sure that all parameters are before the URL's # mark. Example: gid=1545912003.

sheet=sheet_name: Specifies which sheet in a multi-sheet document you are linking to, if you are not linking to the first sheet. 
sheet_name is the display name of the sheet. Example: sheet=Sheet5.
*/
  
  

//send the query - using the "sheet" parametre - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
function drawChart() {
  var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/13ZXjNfFOf0glEzEkAg5VWXNTP3oZPaDR9WKwa0kTrds/gviz/tq?sheet=Sheet2&headers=1&tq=SELECT A, B   where B > 0 and B <= 5 ORDER BY B desc  limit 1000 offset 0');
 query.send(handleSampleDataQuery2Response); //have to change this to handleSampleDataQuery2Response when have more than one chart on the page 
}

//draw the chart -  - using the "sheet" parameter - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
//have to change this to handleSampleDataQuery2Response(response) when have more than one chart on the page
    function handleSampleDataQuery2Response(response){
// ADD some error handling - START
 if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
      }
// ADD some error handling - END

//get data table
var data = response.getDataTable();


//adjust chart and bar height according to how many rows
 var chartAreaHeight = data.getNumberOfRows() * 30;
  var chartHeight = chartAreaHeight + 400;
  
  
  
  // Set chart options - START
   var options = {
//set transparency of the chart background, whether the chart is stacked and importantly, 
//the physical height, in pixels of the chart.
    backgroundColor: 'transparent',
    isStacked: false,
     height: chartHeight,
  

 // control colours of lines NOTE this overides automatic colouring
           colors: ['orange', 'magenta',"blue"],
           //control opacity of bars
            dataOpacity:.85,
            
chartArea: {
      height: chartAreaHeight,
      top: "100",
      right: "100",
      bottom: "100",
      left: "100"
    },
/*An object with members to configure the placement and size of the chart area (where the chart itself is drawn, 
excluding axis and legends). Two formats are supported: a number, or a number followed by %. 
A simple number is a value in pixels; a number followed by % is a percentage.*/
  
  
  
  animation:{startup:'true',duration:'3000',easing:'inAndOut'},
  //makes the chart transparent so the background color shows through
 
      // chart title
          title:'MSQ Results', 
        titleTextStyle: {color: 'white',fontSize:30,fontName: 'arial',bold: false,italic: false},
       // control position of legend
          legend: { position: 'top',textStyle: {color: 'orange', fontSize: 24}},
          
           // horizontal axis title and formating
        vAxis: {
          textPosition:'in',
          title: 'SYMPTOMS',
          titleTextStyle: {color: 'white',fontSize: 24,fontName: 'Arial',bold: false,italic: false},
            textStyle: {color: 'black',fontSize: 13,fontName: 'Arial',bold: false,italic: false},
        gridlines: {color: 'white', count: 5,  units:''},
        minorGridlines: {color: 'green', count:0 ,  units:''}   },
         
          // horizontal axis title and formating
        hAxis: {
        baseline:0,
        baselineColor:'white',
        title: 'SCORE',
           titleTextStyle: {color: 'white',fontSize: 24,fontName: 'Arial',bold: false,italic: false},
                textStyle: {color: 'white',fontSize: 18,fontName: 'Arial',bold: false,italic: false},
            minValue:0, maxValue:4,
            gridlines: {color: 'white', count: 5,  units:''},
            minorGridlines: {color: 'green', count:0 ,  units:''}  },
    
     };
   // Set chart options - END
   


  
//draw the chart
var chart = new google.visualization.BarChart(document.getElementById('mychart2')); //have to change this to mychart2 when have more than one chart on the page 


chart.draw(data,options );



     
   
    
      window.addEventListener('resize', function () {
    chart.draw(data, options);
  }, false);
    
    
   

}
  
</script>
      
<div style="font-family:opensans;border: 0 none; background-color:#009688;">       
     <!-- div to show the chart on the web page --> 
    <div id="mychart2" ></div>  <!--have to change this to mychart2 when have more than one chart on the page-->
    </div>
    
<!--END CHART -->   

 
        
        
        
        
        
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
        </h4>
      </div>
      <div id="collapse3" class="panel-collapse collapse">
        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
      </div>
    </div>
  </div> 
</div>
    
</body>
</html>

【问题讨论】:

  • 需要等到图表的容器可见,然后再绘制图表——同样,google.charts.loadsetOnLoadCallback 应该在每次页面加载时只使用一次...
  • 感谢 WhiteHat - 关于“需要等到图表的容器可见,然后再绘制图表”的任何提示,我可以在我的项目中实现这一点

标签: javascript google-visualization


【解决方案1】:

尝试在手风琴标题点击上绑定重绘:

 $('.panel-heading').click(function(){
      drawChart()
 })

更新

我已经进行了一些重构来完成这项工作:

  1. 删除重复的脚本标签,
  2. 移除 drawChart 重新分配
  3. 添加初始化函数
  4. 添加选项卡 onclick 处理函数

所以主要区别:

初始化从这里开始

   google.charts.setOnLoadCallback(init);

初始化函数

  function init () {

      $.each($('.panel-heading'), function(){
         var chartItem = $(this).parents('.panel').find('.chart-item');
         var chartId = chartItem.attr('id');

         drawChart(chartId);
      })

    }

我们将使用所有选项卡并调用每个 drawChart 函数,为了更容易,我将 .chart-item 类添加到图表 div

OnClick 函数(几乎和 Init 函数做同样的事情)

$('.panel-heading').click(function(){

  var chartItem = $(this).parents('.panel').find('.chart-item');
  var chartId = chartItem.attr('id');

  drawChart(chartId);

})

最后的解决方法:

 function drawChart(chartId) {
      var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/13ZXjNfFOf0glEzEkAg5VWXNTP3oZPaDR9WKwa0kTrds/gviz/tq?sheet=Sheet2&headers=1&tq=SELECT A, B   where B > 0 and B <= 5 ORDER BY B desc  limit 1000 offset 0');


      query.send(function(response){
        handleSampleDataQueryResponse(response, chartId);
      });
  }

我将它重构为

 query.send(function(response){
        handleSampleDataQueryResponse(response, chartId);
      });

为了能够传递chartId

更新 2

为了能够在标签面板中管理图表,您可以使用 drawChart 函数:

function drawChart(chartId) {
  var query;

  if(chartId == 'mychart') {
     query = new google.visualization.Query(' // query for chart1 //');
  }

  if(chartId == 'mychart2') {
     query = new google.visualization.Query(' // query for chart2 //');
  }


  query.send(function(response){
    handleSampleDataQueryResponse(response, chartId);
  });

}

<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>

    <div class="container">
        <h2>Collapse</h2>
        <p><strong>Note:</strong> The <strong>data-parent</strong> attribute makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.</p>
        <div class="panel-group" id="accordion">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
                    </h4>
                </div>
                <div id="collapse1" class="panel-collapse collapse in ">
                    <div class="panel-body">

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                        <br> <br>

                        <div style="font-family:opensans;border: 0 none; background-color:#009688;">
                            <!-- div to show the chart on the web page -->
                            <div class="chart-item" id="mychart"></div>
                        </div>


                    </div>
                </div>
            </div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
                    </h4>
                </div>
                <div id="collapse2" class="panel-collapse collapse">
                    <div class="panel-body">

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                        <br> <br> Chart 2

                        <div style="font-family:opensans;border: 0 none; background-color:#009688;">
                            <!-- div to show the chart on the web page -->
                            <div class="chart-item" id="mychart2"></div>
                            <!--have to change this to mychart2 when have more than one chart on the page-->
                        </div>

                        <!--END CHART -->

                    </div>
                </div>
            </div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
                    </h4>
                </div>
                <div id="collapse3" class="panel-collapse collapse">
                    <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
                </div>
            </div>
        </div>
    </div>


        <!--START CHART -->
<!--First Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Only load the above ONCE per page-->

<script type="text/javascript">
// Load the Visualization API and the corechart package.
//include extra packages that or not included in the corechart package  
// corechart package includes (bar, column, line, area, stepped area, bubble, pie, donut, combo, candlestick, histogram, scatter)
google.charts.load('current', {
    packages: ['corechart', 'annotationchart', 'table']
});
// Set a callback to run when the Google Visualization API is loaded
//google.charts.setOnLoadCallback(drawChart);
google.charts.setOnLoadCallback(init);

/*
The syntax of the query language is composed of the following clauses. 
The order of the clauses must be as follows:

select    Selects which columns to return, and in what order. If omitted, all of the table's columns are returned, in their default order.
where   Returns only rows that match a condition. If omitted, all rows are returned.
group by  Aggregates values across rows.
pivot   Transforms distinct values in columns into new columns.
order by  Sorts rows by values in columns.
limit   Limits the number of returned rows.
offset    Skips a given number of first rows.
label   Sets column labels.
format    Formats the values in certain columns using given formatting patterns.
*/

/*send the query - using the "sheet" parametre not the GID parameter

The query supports the following optional parameters:
headers=N: Specifies how many rows are header rows, where N is an integer zero or greater. 
These will be excluded from the data and assigned as column labels in the data table. 
If you don't specify this parameter, the spreadsheet will guess how many rows are header rows. 
Note that if all your columns are string data, the spreadsheet might have difficulty determining which rows are header rows without this parameter

gid=N: Specifies which sheet in a multi-sheet document to link to, if you are not linking to the first sheet. N is the sheet's ID number. 
You can learn the ID number by navigating to the published version of that sheet and looking for the gid=N parameter in the URL. 
You can also use the sheet parameter instead of this parameter. Gotcha: Google Spreadsheets might rearrange the gid parameter in the URL when viewed in a browser; 
if copying from a browser, be sure that all parameters are before the URL's # mark. Example: gid=1545912003.

sheet=sheet_name: Specifies which sheet in a multi-sheet document you are linking to, if you are not linking to the first sheet. 
sheet_name is the display name of the sheet. Example: sheet=Sheet5.
*/



//send the query - using the "sheet" parametre - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
function drawChart(chartId) {
    var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/13ZXjNfFOf0glEzEkAg5VWXNTP3oZPaDR9WKwa0kTrds/gviz/tq?sheet=Sheet2&headers=1&tq=SELECT A, B   where B > 0 and B <= 5 ORDER BY B desc  limit 1000 offset 0');

    //mychart
    //mychart2
    query.send(function(response){
      handleSampleDataQueryResponse(response, chartId);
    }); //have to change this to handleSampleDataQuery2Response when have more than one chart on the page 
}

//draw the chart -  - using the "sheet" parameter - handleSampleDataQueryResponse) not the GID parameter - (handleQueryResponse)
//have to change this to handleSampleDataQuery2Response(response) when have more than one chart on the page
function handleSampleDataQueryResponse(response, chartId) {
    // ADD some error handling - START
    if (response.isError()) {
        alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
    }
    // ADD some error handling - END

    //get data table
    var data = response.getDataTable();


    //adjust chart and bar height according to how many rows
    var chartAreaHeight = data.getNumberOfRows() * 30;
    var chartHeight = chartAreaHeight + 400;



    // Set chart options - START
    var options = {
        //set transparency of the chart background, whether the chart is stacked and importantly, 
        //the physical height, in pixels of the chart.
        backgroundColor: 'transparent',
        isStacked: false,
        height: chartHeight,


        // control colours of lines NOTE this overides automatic colouring
        colors: ['orange', 'magenta', "blue"],
        //control opacity of bars
        dataOpacity: .85,

        chartArea: {
            height: chartAreaHeight,
            top: "100",
            right: "100",
            bottom: "100",
            left: "100"
        },
        /*An object with members to configure the placement and size of the chart area (where the chart itself is drawn, 
        excluding axis and legends). Two formats are supported: a number, or a number followed by %. 
        A simple number is a value in pixels; a number followed by % is a percentage.*/



        animation: {
            startup: 'true',
            duration: '3000',
            easing: 'inAndOut'
        },
        //makes the chart transparent so the background color shows through

        // chart title
        title: 'MSQ Results',
        titleTextStyle: {
            color: 'white',
            fontSize: 30,
            fontName: 'arial',
            bold: false,
            italic: false
        },
        // control position of legend
        legend: {
            position: 'top',
            textStyle: {
                color: 'orange',
                fontSize: 24
            }
        },

        // horizontal axis title and formating
        vAxis: {
            textPosition: 'in',
            title: 'SYMPTOMS',
            titleTextStyle: {
                color: 'white',
                fontSize: 24,
                fontName: 'Arial',
                bold: false,
                italic: false
            },
            textStyle: {
                color: 'black',
                fontSize: 13,
                fontName: 'Arial',
                bold: false,
                italic: false
            },
            gridlines: {
                color: 'white',
                count: 5,
                units: ''
            },
            minorGridlines: {
                color: 'green',
                count: 0,
                units: ''
            }
        },

        // horizontal axis title and formating
        hAxis: {
            baseline: 0,
            baselineColor: 'white',
            title: 'SCORE',
            titleTextStyle: {
                color: 'white',
                fontSize: 24,
                fontName: 'Arial',
                bold: false,
                italic: false
            },
            textStyle: {
                color: 'white',
                fontSize: 18,
                fontName: 'Arial',
                bold: false,
                italic: false
            },
            minValue: 0,
            maxValue: 4,
            gridlines: {
                color: 'white',
                count: 5,
                units: ''
            },
            minorGridlines: {
                color: 'green',
                count: 0,
                units: ''
            }
        },

    };
    // Set chart options - END



    console.log('chartId111', chartId);

    //draw the chart
    var chart = new google.visualization.BarChart(document.getElementById(chartId)); //have to change this to mychart2 when have more than one chart on the page 


    chart.draw(data, options);


    window.addEventListener('resize', function() {
        chart.draw(data, options);
    }, false);


  }

function init () {

  console.log('init');

  $.each($('.panel-heading'), function(){
     var chartItem = $(this).parents('.panel').find('.chart-item');
     var chartId = chartItem.attr('id');

     console.log('chartId', chartId);

     drawChart(chartId);
  })

}

$('.panel-heading').click(function(){

    var chartItem = $(this).parents('.panel').find('.chart-item');
    var chartId = chartItem.attr('id');

    drawChart(chartId);

})


  
</script>
    
</body>
</html>

【讨论】:

  • 也感谢Leguest。您能否给我一些更多信息,以便我将您的代码实施到我的项目中。我的 JS 技能非常有限。
  • 非常感谢Leguest。将看看这个并集成到我的网站中。会及时通知您。
  • 太棒了。我以你的名字命名了手风琴!!
  • 1/ 我想在手风琴的每个面板中放置一个不同的图表,并且 2/ 让每个手风琴面板独立工作会很困难,即不作为一个组来工作 - 以便不止一个面板可以一次打开。抱歉,我应该在一开始就说明这一点。
  • 我更新了我的答案,但更好的方法是将您的查询和选项管理用于不同的功能,例如query = getChartQuerty(chartId)