事件与行为

用户在 ECharts 图表中可以通过鼠标等方式触发相应的事件。开发者可以监听这些事件,然后通过回调函数做相应的处理,例如,跳转到一个新的链接,或者弹出一个对话框,或者进行数据下钻等等。

ECharts 中的事件名称对应于 DOM 事件名称,均为小写字符串。这是一个绑定 click 事件的例子。

myChart.on('click', function(params) {
  // Print name in console
  console.log(params.name);
});

在 ECharts 中,事件有两种。一种是鼠标事件,在用户鼠标点击或悬浮到图形上时触发。另一种是用户在使用可以交互的组件后触发的行为事件。例如,切换图例(legend)时会触发 'legendselectchanged' 事件(注意,`legendselected` 事件在 ECharts 3 中不再支持),缩放数据区域(dataZoom)时会触发 'datazoom' 事件。

鼠标事件的处理

ECharts 支持常规的鼠标事件,包括 'click''dblclick''mousedown''mousemove''mouseup''mouseover''mouseout''globalout''contextmenu'。下面是一个在柱状图上点击,然后打开对应的百度搜索页面的示例。

// Init the ECharts base on DOM
var myChart = echarts.init(document.getElementById('main'));

// Config
var option = {
  xAxis: {
    data: [
      'Shirt',
      'Wool sweater',
      'Chiffon shirt',
      'Pants',
      'High-heeled shoes',
      'socks'
    ]
  },
  yAxis: {},
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
};
// Use the option and data to display the chart
myChart.setOption(option);
// Click and jump to Baidu search website
myChart.on('click', function(params) {
  window.open(
    'https://www.google.com/search?q=' + encodeURIComponent(params.name)
  );
});

所有的鼠标事件都包含一个参数 params,里面包含了当前数据的各种信息。

格式

type EventParams = {
  // The component name clicked,
  // component type, could be 'series'、'markLine'、'markPoint'、'timeLine', etc..
  componentType: string,
  // series type, could be 'line'、'bar'、'pie', etc.. Works when componentType is 'series'.
  seriesType: string,
  // the index in option.series. Works when componentType is 'series'.
  seriesIndex: number,
  // series name, works when componentType is 'series'.
  seriesName: string,
  // name of data (categories).
  name: string,
  // the index in 'data' array.
  dataIndex: number,
  // incoming raw data item
  data: Object,
  // charts like 'sankey' and 'graph' included nodeData and edgeData as the same time.
  // dataType can be 'node' or 'edge', indicates whether the current click is on node or edge.
  // most of charts have one kind of data, the dataType is meaningless
  dataType: string,
  // incoming data value
  value: number | Array,
  // color of the shape, works when componentType is 'series'.
  color: string
};

判断鼠标点击到了哪里。

myChart.on('click', function(params) {
  if (params.componentType === 'markPoint') {
    // Clicked on the markPoint
    if (params.seriesIndex === 5) {
      // clicked on the markPoint of the series with index = 5
    }
  } else if (params.componentType === 'series') {
    if (params.seriesType === 'graph') {
      if (params.dataType === 'edge') {
        // clicked at the edge of graph.
      } else {
        // clicked at the node of graph.
      }
    }
  }
});

使用 query 来触发指定组件的回调

chart.on(eventName, query, handler);

query 可以是 string 或者 Object

如果是 string,格式可以是 mainType 或者 mainType.subType,例如:

chart.on('click', 'series', function () {...});
chart.on('click', 'series.line', function () {...});
chart.on('click', 'dataZoom', function () {...});
chart.on('click', 'xAxis.category', function () {...});

如果是 Objectquery 可以包含一个或多个属性

{
  ${mainType}Index: number // component index
  ${mainType}Name: string // component name
  ${mainType}Id: string // component id
  dataIndex: number // data item index
  name: string // data item name
  dataType: string // date item type, such as 'node', 'edge'
  element: string // name of element in custom series.
}

例如:

chart.setOption({
  // ...
  series: [
    {
      name: 'uuu'
      // ...
    }
  ]
});
chart.on('mouseover', { seriesName: 'uuu' }, function() {
  // when elements in series named 'uuu' triggered 'mouseover'
});

例如:

chart.setOption({
  // ...
  series: [
    {
      // ...
    },
    {
      // ...
      data: [
        { name: 'xx', value: 121 },
        { name: 'yy', value: 33 }
      ]
    }
  ]
});
chart.on('mouseover', { seriesIndex: 1, name: 'xx' }, function() {
  // when data named 'xx' in series index 1 triggered 'mouseover'.
});

例如:

chart.setOption({
  // ...
  series: [
    {
      type: 'graph',
      nodes: [
        { name: 'a', value: 10 },
        { name: 'b', value: 20 }
      ],
      edges: [{ source: 0, target: 1 }]
    }
  ]
});
chart.on('click', { dataType: 'node' }, function() {
  // call this method while the node of graph was clicked.
});
chart.on('click', { dataType: 'edge' }, function() {
  // call this method while the edge of graph was clicked.
});

例如:

chart.setOption({
  // ...
  series: {
    // ...
    type: 'custom',
    renderItem: function(params, api) {
      return {
        type: 'group',
        children: [
          {
            type: 'circle',
            name: 'my_el'
            // ...
          },
          {
            // ...
          }
        ]
      };
    },
    data: [[12, 33]]
  }
});
chart.on('mouseup', { element: 'my_el' }, function() {
  // when data named 'my_el' triggered 'mouseup'.
});

你可以在回调函数中,根据数据名或系列名,通过数据库查询结果来显示一个弹出窗口或更新图表。下面是一个例子:

myChart.on('click', function(parmas) {
  $.get('detail?q=' + params.name, function(detail) {
    myChart.setOption({
      series: [
        {
          name: 'pie',
          // using pie chart to show the data distribution in one column.
          data: [detail.data]
        }
      ]
    });
  });
});

组件交互事件

ECharts 中所有的组件交互都会触发相应的事件。常用的事件和参数在 events 文档中列出。

下面是一个监听图例事件的例子:

// Show/hide the legend only trigger legendselectchanged event
myChart.on('legendselectchanged', function(params) {
  // State if legend is selected.
  var isSelected = params.selected[params.name];
  // print in the console.
  console.log(
    (isSelected ? 'Selected' : 'Not Selected') + 'legend' + params.name
  );
  // print for all legends.
  console.log(params.selected);
});

通过代码手动触发组件行为

'legendselectchanged' 这样的事件不仅能由用户触发,也可以通过代码手动触发。这可以用来显示提示框(tooltip)或选择图例。

在 ECharts 中,使用 myChart.dispatchAction({ type: '' }) 来触发行为。这种方式可以管理所有的动作,并方便地记录这些行为。

常用的行为和对应的参数在 action 中列出。

下面的例子展示了如何使用 dispatchAction 在饼图中逐个高亮扇区。

option = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b} : {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: [
      'Direct Access',
      'Email Marketing',
      'Affiliate Ads',
      'Video Ads',
      'Search Engines'
    ]
  },
  series: [
    {
      name: 'Access Source',
      type: 'pie',
      radius: '55%',
      center: ['50%', '60%'],
      data: [
        { value: 335, name: 'Direct Access' },
        { value: 310, name: 'Email Marketing' },
        { value: 234, name: 'Affiliate Ads' },
        { value: 135, name: 'Video Ads' },
        { value: 1548, name: 'Search Engines' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

let currentIndex = -1;

setInterval(function() {
  var dataLen = option.series[0].data.length;
  myChart.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
  currentIndex = (currentIndex + 1) % dataLen;
  myChart.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: currentIndex
  });
}, 1000);
在线示例

监听空白区域的事件

有时开发者需要监听从画布空白区域触发的事件。例如,当用户点击空白区域时需要重置图表。

在讨论这个功能之前,我们需要澄清两种事件:zrender 事件和 echarts 事件。

myChart.getZr().on('click', function(event) {
  // This listener is listening to a `zrender event`.
});
myChart.on('click', function(event) {
  // This listener is listening to a `echarts event`.
});

zrender 事件不同于 echarts 事件。前者在鼠标/指针位于任何位置时都会触发,而后者只有在鼠标/指针位于图形元素上时才能触发。实际上,echarts 事件是基于 zrender 事件实现的,也就是说,当一个 zrender 事件在图形元素上触发时,echarts 就会触发一个 echarts 事件。

有了 zrender 事件,我们可以像下面这样实现在空白区域监听事件:

myChart.getZr().on('click', function(event) {
  // No "target" means that mouse/pointer is not on
  // any of the graphic elements, which is "blank".
  if (!event.target) {
    // Click on blank. Do something.
  }
});

贡献者 在 GitHub 上编辑此页

pissangOvilia100pah