1

我正在绘制一张世界地图,并试图从绿色变为红色,即按住鼠标时单击的国家的颜色。我可以通过多次单击来更改颜色,但是当我尝试添加 while 循环时,它只是冻结了。你能帮帮我吗?还有我怎样才能让颜色从绿色循环到红色?意思是一旦它达到红色并且我一直按住鼠标,它就会变成绿色等等...... 这是它的小提琴

var color = d3.scale.linear().domain([0, 50]).range(["green", "red"]);
var pas = [];
var ismousedown = -1;

country
    .on("mousemove", function(d, i) {

        var mouse = d3.mouse(svg.node()).map(function(d) {
            return parseInt(d);
        });

        tooltip.classed("hidden", false)
            .attr("style", "left:" + (mouse[0] + offsetL) + "px;top:" + (mouse[1] + offsetT) + "px")
            .html(d.properties.name);

    })
    .on("mouseout", function(d, i) {
        tooltip.classed("hidden", true);
    })
    .on("mouseup", function(d, i) {
        ismousedown = 0;
    })
    .on("mouseout", function(d, i) {
        tooltip.classed("hidden", true);
    })
    .on("mousedown", function(d, i) {
        ismousedown = 1;
        while (ismousedown == 1) {
            if (pas[d.id]) {
                pas[d.id]++;
            } else {
                pas[d.id] = 1;
            }

            d3.select(this)
                .classed("active", false)
                .style("fill", function(d, i) {
                    return color(pas[d.id]);
                    return d.properties.color;
                });
        }
    });
4

2 回答 2

0

您正在使用一个循环,您之前在其中设置了条件变量,因此它始终为“1”并被卡住。您根本不需要 mousedown 变量,因为您的代码已经处于运行.on("mousedown")状态。我还实现了一个有效的 while 循环。但是颜色变化如此之快,以至于您看不到变化发生。

我建议:

  .on("mousedown", function(d, i) {

      var counter = 0;
      var max_counter = 255;

      while (counter < max_counter) {

          if (pas[d.id]) {

              pas[d.id]++;
          } else {
              pas[d.id] = 1;
          }

          d3.select(this)
              .classed("active", false)
              .style("fill", function(d, i) {
                  return color(pas[d.id]);
                  return d.properties.color; });
          counter++;
      }

  });
于 2017-01-22T17:35:40.490 回答
0

我修改了您的解决方案以使用setInterval()。这将每隔 N 毫秒自动运行一个函数。在此示例中,当鼠标按下时,颜色更新代码将每 10 毫秒运行一次(您可以在 mousedown 函数中调整此设置)。释放鼠标后,间隔将被清除,因此不再运行。

更新了 JSFiddle(注意:我还在函数顶部添加了一些变量)

.on("mousedown", function(d,i) {
  var that = this;
  ismousedown = true;

  colorInterval = window.setInterval(function () {
    // ...
  }, 10); // <== runs every 10 milliseconds
})

.on("mouseup", function(d,i) {
  window.clearInterval(colorInterval);
});
于 2017-01-23T15:59:01.533 回答