简体   繁体   中英

d3.js force cancel a drag event

I have a simple drag event - and if a certain condition is met, I'd like to force cancel the drag currently under way (basically as if you were doing a mouseup).

Something like so:

var drag_behavior = d3.behavior.drag()
.on("drag", function() {
    if(mycondition){
       // cancel the drag event
    }
});

EDIT:

the goal is simply to prevent people from dragging a world map outside certain boundaries in such a way that renders the map in mid-ocean (details below).

Current map code:

var width = window.innerWidth
var height = window.innerHeight

var projection = d3.geo.mercator()
    .scale((width + 1) / 2 / Math.PI)
    .translate([width / 2, height/1.5])
    .precision(.1);

var path = d3.geo.path()
    .projection(projection);

var drag_behavior_map = d3.behavior.drag()
.on("drag", function() {
    drag_click = true //used later to prevent dragend to fire off a click event
    d3.event.sourceEvent.stopPropagation();

    // original idea
    // if(worldmap_left_boundary > 0 || worldmap_right_boundary < screen.height){
    //    cancel or limit the drag here
    // }
});

var svg = d3.select("#map").append("svg")
    .attr("width", width)
    .attr("height", height)
.call(drag_behavior_map)

这应该是不可能的

Basically this should not be possible.

Inside the drag event function, you can use mycondition to decide whether or not to update the dragged element's position. Not updating the position essentially means stopping the drag.

You could also unsubscribe from the drag event:

var drag_behavior = d3.behavior.drag()
  .on("drag", function() {
    if(mycondition) {
       // cancel the drag event
       drag_behavior.on("drag", null);
    }
  });

Note, there would still be a dragend event, unless you unsubscribe that one too.

Alternatively –– though I'm not totally familiar with triggering native events and how that affects d3.behavior.drag() –– you can try triggering a native mouseup event and see what happens.

var drag_behavior = d3.behavior.drag()
  .on("drag", function() {
    if(mycondition) {
      // "this" is the dragged dom element
      this.dispatchEvent(new Event('mouseup'))
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM