ChartJS柱状图实现自定义click事件与hover事件

自定义hover事件:

参考文档:
http://www.chartjs.org/docs/latest/configuration/tooltip.html?h=tooltipmodel#external-custom-tooltips

_this.showTooltip = function(tooltipModel) {
    if (tooltipModel.body) {
        var index = tooltipModel.dataPoints[0].index;
        // Event when user hover on a bar
    } else {
        // Event when mouse leave
    }
};

_this.options = {
    tooltips: {
        enabled: false,
        custom: _this.showTooltip
    }
};

自定义click事件:

参考文档:
http://www.chartjs.org/docs/latest/general/interactions/events.html
http://www.chartjs.org/docs/latest/developers/api.html?h=onclick#getelementatevente

_this.showDetail = function(event, array) {
    var points = _this.chart.getElementAtEvent(event);
    if (points.length > 0) {
        var index = points[0]._index;
        var datasetIndex = points[0]._datasetIndex;
        var color = points[0]._model.backgroundColor);  // 这里的color拿到的是鼠标移到柱状时的高亮色
        // Event when user click a bar
    }
};

_this.options = {
    onClick: _this.showDetail
};

你可能感兴趣的:(JavaScript)