单击d3路径后更改样式 [英] Change style after a d3 path has been clicked

查看:277
本文介绍了单击d3路径后更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I stop the path style being changed if the path has been clicked? I want path style to not be changed after pathHover has been clicked.

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

推荐答案

有多种方法可以实现此目的.由于DDD中的第一个D(也称为D3)表示 data ,因此,我最喜欢的方法是将数据绑定到clicked元素,表明它已被单击:

There are different ways to achieve this. Since the first D in DDD (also known as D3) means data, the approach I like most is binding a datum to the clicked element, indicating that it was clicked:

d.clicked = true;

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

Or, if you want to reverse the boolean after a second click:

d.clicked = !d.clicked;

然后,在mouseover中,只需检查该基准点即可:

Then, in the mouseover, just check that datum:

if (d.clicked) return;

这是一个使用绿色圆圈的演示:如果将鼠标悬停在它们上,它们将变为红色.如果单击它们,它们将变成蓝色,再也不会变成红色(或绿色).

Here is a demo using green circles: if you mouse over them, they turn red. If you click them, they turn blue, and never turn red (or green) again.

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;
  d3.select(this).style("fill", "blue")
})

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

这篇关于单击d3路径后更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆