D3.js通过DOM的事件模型监听用户事件行为,并基于这些事件完成相应功能.常见的事件主要有以下三种:
- 鼠标事件:click,mouseover,mouseout,mousemove等.
- 键盘事件:keydown,keyup等.
- 触控事件:touchstart,touchmove,touchend等.
监听
添加监听事件
监听直接使用 .on() 方法,后面添加事件类型即可.
selection.on(eventType, eventHandler);
- eventType 表示要监听的事件类型,支持w3c制定的所有标准事件类型,具体详见DOM event type.
- eventHandler 回调函数,触发事件后要执行的代码可以写在这里.
监听鼠标单击事件:
// 鼠标单击后将元素渲染为蓝色
d3.select(".class-name")
.on("click", (event) => {
d3.select(this).style('fill', 'blue');
});
获取鼠标位置:
在制作图表时,获取鼠标位置是经常使用的一个功能.
// 使用pointer方法,可以将x和y坐标直接获取
d3.select(".class-name").on('mousemove', function(event) {
const [x, y] = d3.pointer(event);
console.log(`Mouse position: (${x}, ${y})`);
});
处理键盘按钮事件:
// 当按下键盘中的A时,会向svg中添加一个半径为20的橙色小圆
d3.select('body')
.on('keydown', function(event) {
if (event.key === 'a') {
d3.select('svg')
.append('circle')
.attr('cx', Math.random() * 1000)
.attr('cy', Math.random() * 1000)
.attr('r', 20)
.style('fill', '#f60');
}
});
触控事件:
在移动设备,常常需要使用到触控事件,比如拖动某个图标元素.
// 拖动矩形图标时,矩形会跟随手势移动
d3.select('rect')
.call(
d3.drag()
.on('start', function(event) {
d3.select(this).style('fill', 'blue');
})
.on('drag', function(event) {
d3.select(this)
.attr('cx', event.x)
.attr('cy', event.y);
})
.on('end', function() {
d3.select(this).style('fill', 'green');
})
);
删除监听事件
删除事件非常简单,只需要将回调函数设置为null即可.
selection.on(eventType, null);
触发
在实际业务中,常常需要主动去触发某个事件,使用 .dispatch() 即可.
d3.select(".class-name").dispatch("click");