d3.js在鼠标悬停时改变线图点上的颜色和大小

and*_*atz 13 javascript jquery data-visualization d3.js

我用d3.js制作了一个折线图(见附图1).

当鼠标悬停时,我设法在图形点上插入工具提示.我也想改变点的颜色和大小.我试过很多方面,但看起来真的很难.有帮助吗?这是一段代码:

  svg.selectAll("dot")    
    .data(data)         
    .enter().append("circle")                               
    .attr("r", 5.5)
    .style("fill", "#fff8ee")    
       .style("opacity", .8)      // set the element opacity
.style("stroke", "#f93")    // set the line colour
 .style("stroke-width", 3.5) 
    .attr("cx", function(d) { return x(d.date); })       
    .attr("cy", function(d) { return y(d.close); })     
    .on("mouseover", function(d) {   

        div.transition()        
            .duration(70)      
            .style("opacity", .7)

             ;      
        div .html(formatTime(d.date) + "<br/>"  + d.close)  
            .style("left", (d3.event.pageX) + "px")     
            .style("top", (d3.event.pageY - 28) + "px");    
        })                  
    .on("mouseout", function(d) {       
        div.transition()        
            .duration(200)      
            .style("opacity", 0);   
    });
Run Code Online (Sandbox Code Playgroud)

Lar*_*off 35

只需在处理程序中设置颜色和大小:

.on("mouseover", function(d) {
  d3.select(this).attr("r", 10).style("fill", "red");
})                  
.on("mouseout", function(d) {
  d3.select(this).attr("r", 5.5).style("fill", "#fff8ee");
});
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,`this`向我返回了'null`.使用`d3.event.target`代替了. (5认同)

amu*_*lly 7

我不知道为什么,但以前d3.select(this)可以工作,现在就不行了。我现在使用d3.select(event.currentTarget).

因此,如果我们认为svg图形及其所有圆圈默认都是红色的,我们可以将圆圈的颜色更改为绿色mouseover并将颜色返回为红色,mouseout如下所示:

svg.on("mouseover", function(d){
d3.select(event.currentTarget)
.style("fill", "green");
})
.on("mouseout", function(d){
d3.select(event.currentTarget)
.style("fill", "red");
});
Run Code Online (Sandbox Code Playgroud)

  • 请记住,与常规函数相比,箭头函数没有自己的“this”。 (3认同)
  • 谢谢高积云。接受的答案中的代码与 jsfiddle 中的代码不太一样。我已经更新了我自己的代码以匹配您的 jsfiddle 中的代码,我希望它对某人有用。 (2认同)