简体   繁体   English

使用d3时,如何只用鼠标事件触发拖动?

[英]When using d3, how to trigger drag with only mouse events?

There are some discussions around triggering d3 drag programmably.有一些关于以可编程方式触发 d3 拖动的讨论。 Usually people give a work around way.通常人们会给出变通办法。 Like store the drag function and trigger it directly.喜欢存储拖动function直接触发。 So is there a way to trigger d3 drag using mouse events?那么有没有一种方法可以使用鼠标事件触发 d3 拖动? The d3 drag must be implemented according to mouse events. d3 拖动必须根据鼠标事件来实现。 In my app, there are complicated drag setups and expose the drag handlers is not feasible.在我的应用程序中,有复杂的拖动设置并且公开拖动处理程序是不可行的。 Also, I hope the code is tested only on boundaries instead of having to open it up.另外,我希望代码只在边界上进行测试,而不是必须打开它。

I'm wondering how d3 implemented the drag.我想知道 d3 是如何实现拖动的。 I have tried to dispatch mousedown and mousemove events, but it doesn't work.我已尝试调度 mousedown 和 mousemove 事件,但它不起作用。 Here is my testing code.这是我的测试代码。

    const circles = document.querySelectorAll('.edit-handler');
    const clientRect = circles[0].getBoundingClientRect();
    const clientX = (clientRect.left + clientRect.right) / 2;
    const clientY = (clientRect.top + clientRect.bottom) / 2;
    circles[0].dispatchEvent(
        new MouseEvent('mousedown', {clientX, clientY, buttons: 1}));
    circles[0].dispatchEvent(
        new MouseEvent('mousemove', {clientX, clientY, buttons: 1}));
    circles[0].dispatchEvent(new MouseEvent(
        'mousemove',
        {clientX: clientX + 100, clientY: clientY + 100, buttons: 1}));

Ok, I figured it out好吧,我明白了

Looks like the view: window is the deal breaker.看起来像视图:window 是交易破坏者。 I don't quite understand the importance but it works.我不太明白它的重要性,但它确实有效。 If you know why, please make comments to let me and others know.如果你知道为什么,请发表评论让我和其他人知道。

    const circles = document.querySelectorAll('.edit-handler');
    const clientRect = circles[0].getBoundingClientRect();
    const clientX = (clientRect.left + clientRect.right) / 2;
    const clientY = (clientRect.top + clientRect.bottom) / 2;
    circles[0].dispatchEvent(new MouseEvent('mousedown', {
      clientX,
      clientY,
      view: window, // After adding this, it works.
    }));
    circles[0].dispatchEvent(new MouseEvent('mousemove', {
      clientX,
      clientY,
    }));
    circles[0].dispatchEvent(new MouseEvent('mousemove', {
      clientX: clientX + 100,
      clientY: clientY + 100,
    }));
    circles[0].dispatchEvent(new MouseEvent('mouseup', {
      clientX: clientX + 100,
      clientY: clientY + 100,
      view: window, // Here too
    }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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