在mousedown中的Mousemove可以停止鼠标向上发射

时间:2019-07-14 18:24:48

标签: javascript d3.js mouseevent

我正在按住鼠标的同时捕获SVG组(<g>)中的鼠标位置。

但是,mousemove会在释放鼠标按钮后继续触发,并且忽略任何附加mouseup事件的尝试。

var ternary = d3.select("#ternary");

var pointer;
var selector = ternary.append("g");

selector.on("mousedown", function() {
  console.log('down');

  selector.on("mousemove", function() {
    console.log('move');
    var mouse = d3.mouse(this);
    console.log(mouse[0])
    console.log(mouse[1]);
    // continues firing after mouse button released 
    // how do I clear?
  });

  selector.on("mouseup", function() {

    alert('release');
    //this event doesnt fire
  });
});

1 个答案:

答案 0 :(得分:1)

两个注意事项:

  1. 作为容器的<g>元素将采用其内容的大小,这些内容负责鼠标事件;
  2. mouseup确实会触发,如您在此处看到的(仅将<g>的{​​{1}}更改为):

<svg>
var selector = d3.select("svg");

selector.on("mousedown", function() {
  console.log('down');

  selector.on("mousemove", function() {
    console.log('move');
    var mouse = d3.mouse(this);
    console.log(mouse[0])
    console.log(mouse[1]);
    // continues firing after mouse button released 
    // how do I clear?
  });

  selector.on("mouseup", function() {

    alert('release');
    //this event doesnt fire
  });
});
svg {
  background-color: tan;
}

因此,您在这里只有一个可回答的问题:“ [mousemove]在释放鼠标按钮后继续触发,如何清除[it]?”

只需将<script src="https://d3js.org/d3.v5.min.js"></script> <svg></svg>传递给事件处理程序:

null

这是演示:

selector.on("mousemove", null);
var selector = d3.select("svg");

selector.on("mousedown", function() {
  console.log('down');

  selector.on("mousemove", function() {
    console.log('move');
    var mouse = d3.mouse(this);
    console.log(mouse[0])
    console.log(mouse[1]);
    // continues firing after mouse button released 
    // how do I clear?
  });

  selector.on("mouseup", function() {

    selector.on("mousemove", null);

    alert('release');
    //this event doesnt fire
  });
});
svg {
  background-color: tan;
}