2014-10-10 66 views
0

创建简单图表组件时,我无法正确组合拖动,将拖动元素发送到前景并单击。将元素发送到前台时未发出点击

我想什么来实现:

  1. 的拖动或点击的元素应该被发送到前景(在其他元件的前面)
  2. 的选择动作不应该被射出的拖动的元素
  3. 点击或点击应选择一个元素

它适用于其他元素前面的元素,但点击任何其他元素只是将它发送到前面,没有点击。你能帮我解决吗?

的jsfiddle:http://jsfiddle.net/1o1dnpsw/2/

HTML

<svg width="250" height="150"> 
</svg> 
<div id="msg">click on rectangle or drag it</div> 
<p>Problem: while clicking on the element which is not on the foreground (yellow) the click is not emitted.</p> 

CSS

body { font-family: sans-serif; font-size: 12px; } 
svg { border: 1px solid gray; } 
svg rect { border: 1px solid gray; } 
div { border: 1px dotted gray; margin-top: 10px; width: 250px; height: 25px; 
    text-align: center; line-height: 25px; } 

脚本

function select() { 
    document.getElementById('msg').innerText = 
     'selected at ' + new Date().getTime(); 
} 

function addBox(color, x, y) { 
    var r = d3.selectAll('svg').append('rect') 
     .attr('x', x).attr('y', y) 
     .attr('width', 50).attr('height', 50) 
     .attr('fill', color) 
     .on('mousedown', function() { 
      // move element to foreground 
      this.parentNode.appendChild(this); 
     }) 
     .on('click', function() { 
      // do not click when dragged 
      if (d3.event.defaultPrevented) { 
       return; 
      } 
      select(); 
     }) 
     .call(d3.behavior.drag() 
      .origin(function() { return { x : x, y : y }; }) 
      .on('dragstart', function() { 
       d3.event.sourceEvent.preventDefault(); 
      }) 
      .on('drag', function() { 
       x = d3.event.x; 
       r.attr('x', x); 
       y = d3.event.y; 
       r.attr('y', y); 
      }) 
      .on('dragend', function() { 
      })); 
} 

addBox('#FFC60D', 10, 10); 
addBox('#161EFF', 40, 40); 
+1

只是在一个侧面说明:本点击事件在Firefox中完全不起作用。 Chrome很好。 – icecub 2014-10-10 01:31:31

+0

睡前的最后一个注意事项:将innerText()更改为textContent()将为Firefox修复它。 – icecub 2014-10-10 02:52:48

回答

1

修正了它。

小提琴:http://jsfiddle.net/1o1dnpsw/3/

新增2个变量起作用addBox():

var oldX; 
var oldY; 

而改变两者的阻力和dragend事件:

.on('drag', function() { 
    oldX = r.attr('x'); 
    oldY = r.attr('y'); 
    x = d3.event.x; 
    r.attr('x', x); 
    y = d3.event.y; 
    r.attr('y', y); 
}) 
.on('dragend', function() { 
    if (x == oldX && y == oldY) { 
     select(); 
    } 
})); 
+1

基本上它所做的是检查你是否实际拖动它。如果没有,它会触发select()事件。 – icecub 2014-10-10 02:12:42