单击d3路径后更改样式

时间:2017-10-05 02:27:44

标签: javascript d3.js

如果单击路径,如何停止更改路径样式?我希望在点击pathHover后不要更改路径样式。

let pathHover = this.svg.append('path')
    .data([data])
    .attr('class', 'line-padded')
    .attr('d', line);

pathHover.on('mouseover', function() {
    console.log('path mouse over');
    path.style('stroke-width', 6);
});

pathHover.on('mouseleave', function() {
    path.style('stroke-width', 4);
});

pathHover.on('click', function() {
    console.log('clicked');
    path.style('stroke', 'blue');
    path.style('stroke-width', 6);
});

2 个答案:

答案 0 :(得分:1)

有不同的方法来实现这一目标。由于DDD中的第一个D(也称为D3)意味着数据,我最喜欢的方法是将一个数据绑定到被点击的元素,表明它被点击了:

d.clicked = true;

或者,如果您想在第二次点击后反转布尔值:

d.clicked = !d.clicked && true;

然后,在mouseover中,只需检查该数据:

if (d.clicked) return;

以下是使用绿色圆圈的演示:如果将鼠标悬停在它们上方,它们会变为红色。如果单击它们,它们会变为蓝色,并且永远不会再变为红色(或绿色)。



var svg = d3.select("svg");
var circles = svg.selectAll(null)
  .data(d3.range(5).map(function(d) {
    return {
      x: d
    }
  }))
  .enter()
  .append("circle")
  .attr("cursor", "pointer")
  .attr("cy", 75)
  .attr("cx", d => 30 + 50 * d.x)
  .attr("r", 20)
  .style("fill", "lime");

circles.on("mouseover", function(d) {
  if (d.clicked) return;
  d3.select(this).style("fill", "firebrick")
}).on("mouseout", function(d) {
  if (d.clicked) return;
  d3.select(this).style("fill", "lime")
}).on("click", function(d) {
  d.clicked = !d.clicked && true;
  d3.select(this).style("fill", "blue")
})

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
&#13;
&#13;
&#13;

编辑:

关于使用d.clicked = !d.clicked && true;

在JavaScript中,AND运算符(&amp;&amp;)返回第一个值,如果它是假的......

&#13;
&#13;
console.log(undefined && true)
&#13;
&#13;
&#13;

......或者第二个,如果第一个是真的:

&#13;
&#13;
console.log(true && "Foo")
&#13;
&#13;
&#13;

第一次点击该元素时,没有d.clicked,因此它是undefined。否定它会将其变为true,因此会返回true

如果有d.clicked属性,则会被取消,变为false,因此会返回false

答案 1 :(得分:0)

可能是一些策略,

为点击的路径设置path.style("pointer-events", "none"),这将停止所有未来的点击/鼠标悬停事件。

或者,如果这太过激烈,请在单击路径path.classed("clicked", true)中添加一个类,您可以在鼠标悬停事件期间在测试中使用该类,然后再应用任何样式更改