D3js highlight bar one by one continuously

萝らか妹 提交于 2020-01-16 19:10:28

问题


Here is the sample fiddle

Below code is to create bar

      svg.selectAll("rect")
   .data(dataset, key)
   .enter()
   .append("rect")
   .attr("x", function(d, i) {
        return xScale(i);
   })
   .attr("y", function(d) {
        return h - yScale(d.value);
   })
   .attr("width", xScale.rangeBand())
   .attr("height", function(d) {
        return yScale(d.value);
   })
   .attr("fill", function(d) {
        return "blue";
   })

    //Tooltip
    .on("mouseover", function(d) {
        d3.select(this).style("fill","red");
    })
    .on("mouseout", function() {
        d3.select(this).style("fill","blue");
    })  ;

On mouseover bar gets red color, and on mouseout it gets back to blue color,

I want it to continuously get red color one by one means first bar red then second bar, then third, after moving ahead previous bar should restore its origin color, there will be only one red bar at a time. and it should be like when it reach to end, it should again start from beginning


回答1:


Here is the result: http://jsfiddle.net/DavidGuan/f07wozud/4/

Code I added:

function reRenderColor() {
  svg.selectAll("rect")
      .transition()
      .delay(function(d, i){ return i* 500 })
      .duration(200)
      .style('fill', 'red')
      .transition()
      .delay(function(d, i){ return i* 500 + 400 })
      .duration(200)
      .style('fill', 'blue')
}  

reRenderColor();
setInterval(reRenderColor, svg.selectAll("rect").size() * 500 + 500)  



回答2:


I gave .attr("id", function(d,i){return "rect"+i;}); to your rect elements in order to select them. Then, I used a recursive setTimout function to solve this with d3 transition property.

 var z = 0;
  var timeoutFunc = function(){ 
  setTimeout(function(){
    if(z < 20){
      d3.select("#rect"+ z).transition().duration(350).attr("fill","red")
                           .transition().delay(550).attr("fill","blue");       
      z++;
      timeoutFunc();
    }else if(z == 20){
        z = 0;
      timeoutFunc();
    }    
  },500);
  };

Here's an updated fiddle.

Note that durations could be changed for a better color visualization but this will give you an idea.

http://jsfiddle.net/51Lsj6ym/5/




回答3:


Hope this is what you want

//Tooltip
.on("mouseover", function(d) {
    d3.selectAll("rect").style("fill","blue");
    d3.select(this).style("fill","red");
})
.on("mouseout", function() {
})  ;

fiddle



来源:https://stackoverflow.com/questions/36735709/d3js-highlight-bar-one-by-one-continuously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!