如何在谷歌折线图上点击线

时间:2016-07-06 15:02:30

标签: javascript google-visualization linechart clickable linegraph

我想制作一个带有可点击线条的谷歌折线图,但我似乎只能使数据点可点击。是否有可能使数据点之间的线可以点击?

1 个答案:

答案 0 :(得分:2)

使用配置选项focusTarget: 'category'

单击该行时,将选择最近的点。

虽然,在我当前的浏览器中,我必须抓住鼠标的重点,
在它之前~2px会让我点击。

但与focusTarget: 'datum'相比确实有效 只允许点击点

见下面的工作片段......



google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'X');
    data.addColumn('number', 'Y');
    data.addRows([
      [0, 0],
      [6, 11],
      [12, 30],
      [18, 52],
      [24, 60],
      [30, 55],
      [36, 62],
      [42, 63],
      [48, 72],
      [54, 71],
      [60, 64],
      [66, 70]
    ]);

    // clickable line
    new google.visualization.LineChart(document.getElementById('chart_div0')).draw(data, {
      focusTarget: 'category'
    });

    // point only
    new google.visualization.LineChart(document.getElementById('chart_div1')).draw(data, {
      focusTarget: 'datum'
    });
  },
  packages:['corechart']
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>click line</div>
<div id="chart_div0"></div>
<div>point only</div>
<div id="chart_div1"></div>
&#13;
&#13;
&#13;

编辑

如果focusTarget: 'category'无法解决问题, 另一种选择是使用'click' event

虽然没有任何重点,也没有显示工具提示,但该线仍然是可点击的 但点击的位置需要相当精确 您可以使用targetID来确定点击的行/ ...

请参阅以下摘录...

&#13;
&#13;
google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'X0');
    data.addColumn('number', 'Y0');
    data.addColumn('number', 'Y1');
    data.addRows([
      [0, 0, 0],
      [6, 11, 7],
      [12, 30, 13],
      [18, 52, 19],
      [24, 60, 25],
      [30, 55, 31],
      [36, 62, 37],
      [42, 63, 43],
      [48, 72, 49],
      [54, 71, 55],
      [60, 64, 61],
      [66, 70, 67]
    ]);

    var chart = new google.visualization.LineChart(document.getElementById('chart_div1'));

    google.visualization.events.addListener(chart, 'click', function (props) {
      if (props.targetID.indexOf('line') > -1) {
        var hAxis = chart.getChartLayoutInterface().getHAxisValue(props.x);
        var vAxis = chart.getChartLayoutInterface().getVAxisValue(props.y);
        document.getElementById('chart_div0').innerHTML = props.targetID + ' clicked at [' + hAxis + ', ' + vAxis + ']';
      }
    });

    chart.draw(data, {
      lineSize: 3,
      pointSize: 5
    });
  },
  packages:['corechart']
});
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div0">line click result shown here</div>
<div id="chart_div1"></div>
&#13;
&#13;
&#13;