d3.js 在选择上附加基本事件
示例
通常,您将需要为对象创建事件。
function spanOver(d,i){ var span = d3.select(this); span.classed("spanOver",true); } function spanOut(d,i){ var span = d3.select(this); span.classed("spanOver", false); } var div = d3.select('#divID'); div.selectAll('span') .on('mouseover' spanOver) .on('mouseout' spanOut)
此示例将鼠标spanOver悬停在具有ID的div内的跨度上时添加类,divID并在鼠标退出跨度时将其删除。
默认情况下,d3将传递当前跨度和索引的原点。this上下文也是当前对象,这非常方便,因此我们可以对其进行操作,例如添加或删除类。
您也可以只在事件上使用匿名函数。
div.selectAll('span') .on('click', function(d,i){ console.log(d); });
数据元素也可以添加到当前选定的对象。
div.selectAll('path') .on('click', clickPath); function clickPath(d,i) { if(!d.active) { d.active= true; d3.select(this).classed("active", true); } else { d.active= false; d3.select(this).classed("active", false); } }
在此示例中,未触发click事件之前未在选择中定义active。如果您要返回路径选择,尽管所有单击的对象都将包含active键。