How to listen to drag event of CytoscapeJS node (including only the one directly under the cursor/finger)

时间秒杀一切 提交于 2021-01-29 16:24:17

问题


I am using Cytoscape JS to create a web browser-based graph manipulation tool. I am facing a problem in listening the drag event of multiple selection of nodes.

I could listen to 'drag' event of nodes using the following code:

cy.on('drag', 'node', function (e) {
  let draggedNode = e.target
  ...
}

However, when I drag several nodes at once, the event is triggered to all selected nodes individually.

What I want to accomplish is to listen to drag event of a node where several nodes are currently selected, but only listen to the element directly (including only the one node directly under the cursor or the user’s finger). So that whenever I drag multiple selected nodes at once, the event only triggered to the one that being dragged under the finger or cursor only.

This is similar to grabon, freeon dragfreeon events that is currently available to CytoscapeJS. However, there is no dragon event for this. I don't want to listen to drag event of all currently selected node events. But only the one that is currently under the cursor/finger.

I have been trying to find the cursor position from the passed e parameter, so that I can test whether the cursor is currently over the current triggering node or not. However the position and renderedPosition attributes values were found to be undefined. So I can't do the cursor position test.

Therefore, is someone out there know how to implement this in Javascript? Thank you.


回答1:


You could use grabon, free or similar to detect the target, add a class to it, and listen to drag events only for nodes of that class.

The item.isNode() check in the code below is kinda pointless.

cy.on('grabon', 'node', (e) => {
    let item = e.target;

    if (item.isNode()) {
        item.addClass('drag-parent');
    }
});

cy.on('free', 'node', (e) => {
    let item = e.target;

    if (item.isNode() && item.hasClass('drag-parent')) {
        item.removeClass('drag-parent');
    }
})

cy.on('drag', 'node.drag-parent', (e) => {
    let item = e.target;

    console.warn(item.id());
})


来源:https://stackoverflow.com/questions/61380170/how-to-listen-to-drag-event-of-cytoscapejs-node-including-only-the-one-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!