【问题标题】:How can I listen mouse events from d3 when jquery drag & drop is in action?当 jquery 拖放操作时,如何从 d3 监听鼠标事件?
【发布时间】:2014-04-07 10:58:41
【问题描述】:

我打算使用 jquery 将 dom 节点拖到 svg 上并放置它们,以便 d3 可以处理放置。 This so question 给了我一个很好的起点。

当我从 d3 监听 mousemove 事件时,d3 在 jquery 的拖动操作期间似乎无法正确跟踪鼠标移动。我想让 d3 在放置之前响应拖动,为此我需要跟踪 jquery 在 svg 之外启动的拖动。

我已经修改了上述问题中的小提琴,以演示不起作用的方法。可以看here

这是小提琴的代码:

var treeCreator = function(){}; 


  treeCreator.prototype.callbacktest = function(svgContainer){
  alert('the element has been dropped');
  }; 

  treeCreator.prototype.createTreeNode = function(theSVG){
      $('#tobeDropped').remove();
      theSVG.append("circle")
        .style("stroke","green")
        .style("fill","white")
        .attr("r",40)
        .attr("cx", 100)
        .attr("cy", 100)
        .on("mouseover", function () {
            d3.select(this).style("fill", "aliceblue");
        })
            .on("mouseout", function () {
            d3.select(this).style("fill", "red");
        }); 
 }; 

 $(document).ready(function(){

    $('#tobeDropped').draggable({containment:'#mainContainer'});

var theSVG = d3.select('#dropInSVG')
.append("svg")
.attr("width",200)
.attr("height",200);

var positionLabel = theSVG.append("text")
                .attr("x", 10)
                .attr("y", 30).text("begin log");
 theSVG.on("mousemove", function () {
            var position = d3.mouse(this); 
            positionLabel.text(position);
        });

var tc = new treeCreator(); 

$('#dropInSVG').droppable({
    drop: function(){
        tc.createTreeNode(theSVG); 
    }
});

  });

当 jquery 拖动不动作时,mousemove 侦听器会正确更新标签,但在拖动期间无法这样做。它会执行一些更新,但它是不可预测且不完整的。

我正在尝试做的事情可能吗?

【问题讨论】:

    标签: jquery d3.js event-handling


    【解决方案1】:

    这对我来说可能更像是一个黑客而不是一个解决方案,但你总是可以听drag

    function updatePosition() {
      var position = d3.mouse(theSVG.node()); 
      positionLabel.text(position);
    }
    
    var dragging = false; 
    
    $('#tobeDropped').draggable({
      containment: '#mainContainer',
      start:       function() { dragging = true; },
      stop:        function() { dragging = false; },
      drag:        updatePosition
    });
    
    theSVG.on("mousemove", function () {
      if (dragging) return; 
      updatePosition();
    });
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2011-09-19
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      相关资源
      最近更新 更多