d3.js change circle radius on mouse events [duplicate]

巧了我就是萌 提交于 2020-12-15 06:20:37

问题


I have circles that I've drawn in d3.js v5. I'm getting the mouse over events as expected, and I can log stuff to the console and everything looks right. The only part that isn't working is when I try and set the radius to be larger. The radius size isn't changing.

function handleMouseOver(d, i) {   
    console.log("over ", d, i);
    console.log("this", this)
    d3.select(this).attr({
        r: 8
    });
}

function handleMouseOut(d, i) {   
    console.log("out ", d, i);
    d3.select(this).attr({
        r: 4
    });
}

Here is the part where the circles are drawn.

linesAndDots
    .selectAll(".data-circle")
    .data(d=>d.values)
    .enter()
    .append("circle")
    .attr("class", "data-circle")
    .attr("r", 5)
    .attr("cx", function(d) {
      return xScale(d.date);
        })
    .attr("cy", function(d) {
      return yScale(d.measurement)
     })
     .on("mouseover", handleMouseOver)
     .on("mouseout", handleMouseOut);

Here is the small reproducible demo: http://plnkr.co/edit/23etevpozYBTpXdH


回答1:


Change the handleMouseOver and handeMouseOut as following:

function handleMouseOver(d, i) {       
    d3.select(this).transition()
        .duration(1)
        .attr("r", 20);
}

function handleMouseOut(d, i) {   
    d3.select(this).transition()
        .duration(1)
        .attr("r", 4);
}

You can't change the styling using just the .attr attribute, you'll need to define a transition() (docs).

Updated snippet: Click here




回答2:


Looking at your code you are setting r like this

.attr("r", 5)

but than you are using

.attr({ r: 8 });

Maybe you need to use this

d3.select(this).attr("r", 8);

Never use d3js just a though



来源:https://stackoverflow.com/questions/64065612/d3-js-change-circle-radius-on-mouse-events

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