如何在将鼠标悬停在图表的点上时将光标样式更改为指针?

时间:2016-12-07 09:53:07

标签: javascript chart.js

我正在使用chart.js v.2。我试图在用户将鼠标悬停在图表点上时将光标样式更改为“指针”。 (我将使用它与条形图,饼图,折线图)。似乎应该在charts.js v.2中支持这个选项。但我无法在任何地方找到一个例子。

编辑: 我没有提到我使用图表做出反应,更具体地说我正在使用这个https://github.com/scrapinghub/splash/blob/master/splash/browser_tab.py#L655

我正在导入,例如图表行import { Line } from 'react-chartjs-2';

class ChartTimelineChart extends Component {



constructor(props){
    super(props);

    this.options = {
       responsive: true,
       maintainAspectRatio: false,
       animation: {
            easing:  'easeOutCirc',
            duration: 1000
      },
      pointStyle : 'circle',
            scales: {
                 xAxes: [{
                     display: true,
                     gridLines: {display: false},
                     scaleLabel: {display: true}
                }],
                yAxes: [{
                    display: true,
                    gridLines: {display: false},
                    ticks: {beginAtZero:true},
                    scaleLabel: {display: true}
               }]
           },
      tooltips: {
        displayColors: false
      },
      legend: false
    };


   searchChart(elem, props, data) {
    //Something... 
   }

  render(){

    return (
        (this.props.selectedYears.length)
        ? (  <div>
          <Line data={this.props.selectedYearsData}
                redraw={true}
                options={this.options}
                getElementAtEvent={elem => this.searchChart(elem, this.props, this.props.selectedYearsData)} />
        </div>)
        : <Line data={{datasets: [], labels: []}}
                redraw={true}
                options={this.options} />
    )
  }
};

2 个答案:

答案 0 :(得分:2)

在Chart.js 2.x中,我使用了这种方法。只需将其添加到选项中即可:

events: ['mousemove'], // this is needed, otherwise onHover is not fired
onHover: (event, chartElement) => {
    event.target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}

希望有帮助。

答案 1 :(得分:1)

我刚刚为条形图做了这件事,但我相信这个解决方案对你也有用。 有一个名为&#34; chart-hover&#34;的属性,您可以在其中设置回调。每次进入和离开图表栏时都会触发它。

这就是我的 canvas 的样子:

<canvas id="bar-material" chart-hover="onHover" class="chart-horizontal-bar"  chart-data="chartData" chart-labels="labels" chart-series="series" chart-colors="colors" chart-options="options" chart-click="onClick" height="160">
</canvas>

onHover 在我的控制器上的显示方式:

$scope.onHover = function (points, evt) {
    if (points.length === 0) {
      evt.toElement.attributes.style.nodeValue = evt.toElement.attributes.style.nodeValue.replace("cursor: pointer;", "")
      return;
    }
    var res = evt.toElement.attributes.style.nodeValue.match(/cursor: pointer;/);
    if (res == null) {
      evt.toElement.attributes.style.nodeValue += "cursor: pointer;"
    }
};
相关问题