【问题标题】:d3.js change color and size on line graph dot on mouseoverd3.js 在鼠标悬停时更改折线图点的颜色和大小
【发布时间】:2014-07-05 08:49:22
【问题描述】:

我用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);   
    });

【问题讨论】:

    标签: javascript jquery d3.js data-visualization


    【解决方案1】:

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

    .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");
    });
    

    【讨论】:

    • 额外的d3.select(this)... 将被放置在mouseovermouseout 处理程序中,就像我已经说明的那样。
    • 出于某种原因,thisnull 返回给我。使用 d3.event.target 代替工作。
    【解决方案2】:

    我不知道为什么,虽然 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");
    });
    

    【讨论】:

    • 您的假设是错误的:this 的绑定仍然按照记录和接受的答案中的规定工作。有关工作演示,请参阅 jsfiddle.net/4xjnfqL7/2。当然,您的方法也有效,尽管它不必要地复杂。您的代码的上下文可能很重要,因为它可能会更改 this 的绑定,但由于您没有提供任何内容,因此我认为这没有帮助。
    • 感谢高积云。接受的答案中的代码与您的 jsfiddle 中的代码不完全相同。我已经更新了自己的代码以匹配您的 jsfiddle 中的代码,我希望它对某人有用。
    • 小提琴中的代码与接受的答案中的代码几乎相同。不过,我添加了两个没有任何副作用的日志语句。你现在的回答方式是完全错误的,而且行不通;您正在尝试选择一个布尔值!这不等同于我在小提琴中的内容,也不匹配问题或接受的答案。
    • 除非你有一个工作演示来证明你声称d3.select(this) 不再工作,否则我建议你重新考虑这篇文章并考虑完全删除它。
    • 请记住,与常规函数相比,箭头函数没有自己的this
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多