繁体   English   中英

D3:.transition()不处理事件

[英]D3: .transition() not working with events

我正忙着在Angular4中使用D3绘制条形图。

// Enter Phase
this.chart.selectAll('.bar')
  .data(this.barData)
  .enter()
  .append('rect')
  .attr('class', 'bar');

// Update Phase
let bars = this.chart.selectAll('.bar').transition()
  .attr('x', (d) => {return this.x(this.parseTime(d.date.toUpperCase()));})
  .attr('y', (d) => {return this.y(d.point)})
  .attr('width', 15)
  .attr('height', (d) => {return this.charDimensions.height - this.y(d.point);})
    .on("mouseover", function (d) {D3.select(this).style('opacity', 0.5);})
    .on("mouseout", function (d) {D3.select(this).style('opacity', 1);})
    .on("click", (d) => {this.barClicked.emit(d);});

// Exit phase
this.chart.selectAll('.bar')
  .data(this.barData)
  .exit().remove();

在我的绘图方法中,当我调用animate()我收到一个错误: Error: unknown type: mouseover 这是有道理的,因为我可能试图在D3返回的转换上调用on("<event>") ,转换效果就在那里,但是,转换后的所有内容都会中断,即:动画有效,但是密谋打破了。

但是,当我尝试执行以下操作时:

// Update Phase
let bars = this.chart.selectAll('.bar');
bars.transition();
bars.attr('x', (d) => {return this.x(this.parseTime(d.date.toUpperCase()));})
  .attr('y', (d) => {return this.y(d.point)})
  .attr('width', 15)
  .attr('height', (d) => {return this.charDimensions.height - this.y(d.point);})
    .on("mouseover", function (d) {D3.select(this).style('opacity', 0.5);})
    .on("mouseout", function (d) {D3.select(this).style('opacity', 1);})
    .on("click", (d) => {this.barClicked.emit(d);});

没有错误发生,但没有任何反应,新数据集没有转换效果。

这里的问题是两个使用相同名称的不同方法之间的混淆:

由于你有转换选择,当你写...

.on(...

该方法期望看到三件事(或类型名称):

  • “开始”
  • “结束”
  • “打断”

但是,“mouseover”,“mouseout”或“click”都不是。 然后你得到你的错误......

> Uncaught Error: unknown type: mouseover

方案

将事件侦听器绑定到常规选择。 然后,在此之后,创建您的转换选择。

因此,在您的情况下,将所有on侦听器绑定到“enter”选项(顺便说一句,这更有意义),将它们从更新选择中删除。

看看这个小小的演示。 首先,我创建一个常规的输入选择,我添加了事件监听器:

var bars = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    //some attr here
    .on("mouseover", function(d) {
        console.log(d)
    });

然后,我添加过渡:

bars.transition()
    .duration(1000)
    etc...

将鼠标悬停在条形图上以查看“鼠标悬停”工作:

 var svg = d3.select("svg"); var data = [30, 280, 40, 140, 210, 110]; var bars = svg.selectAll(null) .data(data) .enter() .append("rect") .attr("x", 0) .attr("width", 0) .attr("y", function(d, i) { return i * 20 }) .attr("height", 18) .attr("fill", "teal") .on("mouseover", function(d) { console.log(d) }); bars.transition() .duration(1000) .attr("width", function(d) { return d }) 
 .as-console-wrapper { max-height: 25% !important;} 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg></svg> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM