【问题标题】:How to change HTML style in ChartOption with if condition?如何使用 if 条件更改 ChartOption 中的 HTML 样式?
【发布时间】:2015-04-03 16:08:03
【问题描述】:

我正在使用 Chart.js 在我的网站中绘制图表。问题是,如果数据值为 0,我需要更改图形数据的样式。

例如我有数组(array1),其中包含以下数据: 0; 0; 0.125; 0; 0; 0;

所以这会显示这样的聊天:

生成样式的代码是这样的:

function MoreChartOptions(){} 
        var ChartData = {
        labels : labelsArray,
        datasets : [{
            fillColor : "rgba(52,152,219,1)",
            strokeColor : "rgba(52,152,219,0.5)",
            pointColor : "rgba(52,152,219,1)",
            markerShape :"circle",
            pointStrokeColor : "rgba(255,255,255,1.00)",
            data : array1,
            },
        ]};
ChartOptions= {canvasBackgroundColor:'rgba(255,255,255,1.00)',spaceLeft:12,spaceRight:12,spaceTop:12, ...

我的问题是:如果图表数据的值为 0,如何更改(如果可能)ChartOptions 样式(字体大小 - inGraphDataFontSize:12)?

我试过这个,但它不起作用:

ChartOptions=
{canvasBackgroundColor:'rgba(255,255,255,1.00)', ...
...,
for(a=0;a<array1.length;a++){array1[a] != 0 ? inGraphDataFontSize:12 : inGraphDataFontSize:5}, ...

非常感谢您的帮助。

【问题讨论】:

  • 调试器显示的错误是这样的:“Uncaught SyntaxError: Unexpected token (”它在所有 ChatOptions 下划线

标签: javascript styles chart.js


【解决方案1】:

当您使用 new Chart(....) 语句创建图表时,您会返回一个图表对象,您可以操作和刷新(使用 update() 函数)。

因此,例如,如果您希望 0 值条为红色,您可以执行以下操作:

var myBarChart = new Chart(document.getElementById("myChart").getContext("2d")).Bar(ChartData, ChartOptions);

for (var key in myBarChart.datasets[0].bars) {
    if (myBarChart.datasets[0].bars[key].value == 0) {
        // Change 2nd bar to red (display).
        myBarChart.datasets[0].bars[key].fillColor = "rgba(255,0,0,0.7)";
        myBarChart.datasets[0].bars[key].strokeColor = "rgba(255,0,0,1)";
        // Change 2nd bar to red (highlight setting on mouse over)
        myBarChart.datasets[0].bars[key].highlightFill = "rgba(212,10,10,0.7)";
        myBarChart.datasets[0].bars[key].highlightStroke = "rgba(212,10,10,1)";
    }
}

myBarChart.update();

You can see what it looks like in a jsfiddle here.

【讨论】:

    【解决方案2】:

    您可以在 chart.js v3 中为此使用可编写脚本的选项,如下所示:

    var options = {
      type: 'bar',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [0, 19, 0, 0, 0, 0],
          backgroundColor: ctx => (ctx.raw === 0 ? 'red' : 'blue'),
          minBarLength: 10
        }]
      },
      options: {}
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
    </body>

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 2011-01-06
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      相关资源
      最近更新 更多