Javascript d3:有没有办法以编程方式停止拖动项目? [英] Javascript d3: Is there a way to programmatically stop dragging an item?

查看:114
本文介绍了Javascript d3:有没有办法以编程方式停止拖动项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击并拖动项目时.有没有办法让它在不松开鼠标键的情况下停止可拖动?

When I'm clicking and dragging an item. Is there a way to forcefully make it stop being draggable without letting go of the mouse button?

例如,如果我将某个项目拖到某个边界框上,是否可以让它放开被拖的项目?

For example, if I drag an item across a certain boundary box, can I make it let go of the dragged item?

推荐答案

jsfiddle示例.我从另一个用户派生了一个拖动示例,并在代码中添加了工作边界.单击以创建一个圆,然后将其拖到蓝色框上以查看其工作状态.

jsfiddle example. I forked a drag example from another user, have added a working boundary in the code. Click to create a circle, then drag it over the blue box to see it working.

此处的概念是观察x&在拖动对象时,y坐标在d3.event中,然后触发以下两种方式之一的停止"事件.缺点是,在拖动事件收到mouseUp之前,它会在仍然按住鼠标的同时引发错误.

The concept here is to observe the x & y coordinates in d3.event while an object is being dragged, then trigger the 'stop' event one of two ways as shown below. The drawback is that until the drag event receives a mouseUp, it throws an error while the mouse is still being held down.

// Define drag beavior
var drag = d3.behavior.drag()
    .on("drag", dragmove);

function dragmove(d) {
    // if the event.x goes over a boundry, trigger "dragend"
    if(d3.event.x > 200){

        // using D3 
        drag.dragend(); 

       // or using jquery 
       drag.trigger("dragend");
    }
  var x = d3.event.x;
  var y = d3.event.y;
  d3.select(this).attr("transform", "translate(" + x + "," + y + ")");
}

此处的边界基于一个变量-x位置,但可以扩展为基于形状的表面积.

The boundary here is based on one variable - x location, but can be extended to be based on the surface area of a shape.

拖动被用作此事件的名称空间,D3为此事件创建了调度程序对象(请参阅D3库代码).可以通过调用事件名称来访问它(例如)

Drag is being used as the namespace for this event, an event for which D3 creates a dispatcher object (see the D3 library code). That can be accessed by calling the event name (for example)

drag.on("eventName", functionToDo)
drag.eventName();

或者,如果您想使用JQuery,则可以使用以下方式应用触发器:

Or if you want to use JQuery then a trigger can be applied using:

drag.trigger("dragend")

将鼠标悬停事件附加到边界框"不起作用,因为要拖动的对象将在鼠标和框之间.也许那里也有解决方法.我包括了另一个较小的红色框(打开控制台以查看此正常工作).

Attaching a mouseover event to a 'boundary box' doesn't work as the object being dragged would be between the mouse and the box. Maybe there is a workaround there also. I have included another smaller red box (open the console to see this not working).

来源:

https://github.com/mbostock/d3/wiki/Drag-Behavior

https://github.com/mbostock/d3/wiki/Internals#dispatch_on

http://api.jquery.com/trigger/

这篇关于Javascript d3:有没有办法以编程方式停止拖动项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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