d3.js:区分拖动/开始/结束和单击事件 [英] d3.js : Differentiate between drag/start/end and click event

查看:127
本文介绍了d3.js:区分拖动/开始/结束和单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我有一个对象,我需要它所有的拖动和单击事件.有一些讨论关于此问题,但主要涉及单击和拖动事件.(并且回复提琴无法正常工作)

我在这里有小提琴.当我拖动时,单击被阻止,但是当我单击dragstart和end事件时将触发.我希望它们在单击时不触发,而在拖动时不要单击.

  var drag = d3.behavior.drag().origin(function(d){return d}).on('drag',function(d){d3.select(this).attr('cx',function(d){return d.x + = d3.event.dx});d3.select(this).attr('cy',function(d){return d.y + = d3.event.dy});console.log('拖动');}).on('dragstart',function(d){d3.event.sourceEvent.stopPropagation()console.log('拖动开始');}).on('dragend',function(d){console.log('拖动结束');})//.....MySvgElementWith3DStuffOnIt.on('click',function(){if(d3.event.defaultPrevented)返回;console.log('clicked');}); 

解决方案

您的示例按预期工作.查看更新的提琴: https://jsfiddle.net/thatOneGuy/dd4nujxo/1/

我已经添加了一些控制台日志.当您拖动此行时:

  if(d3.event.defaultPrevented){console.log('return');返回}; 

将停止触发点击事件.而且,当您仅单击时, dragstart dragend 会被触发(按预期方式),但 drag 不会.这就是为什么要放置代码以在 drag 函数中移动圆的原因.整个过程都按预期进行:)

As the title says, I have an object, and i need all it's drag and click events. There was some discussion about this issue, but it mainly concerned the click and drag events. (and a reply fiddle didnt work properly)

I have a fiddle here of where I am at. When I drag, click is prevented, but when I click the dragstart and end events fire. I'd like them not to fire when I click, and I'd like click not to fire when I want to drag.

var drag = d3.behavior.drag()
  .origin(function(d){return d})
  .on('drag', function(d){
   d3.select(this).attr('cx', function(d){ return d.x += d3.event.dx });
   d3.select(this).attr('cy', function(d){ return d.y += d3.event.dy });   
   console.log('dragging');
})
.on('dragstart', function(d){
  d3.event.sourceEvent.stopPropagation()
  console.log('drag start');
})
.on('dragend', function(d){
  console.log('drag end');
})

// ..... 

 MySvgElementWith3DStuffOnIt.on('click', function(){
  if(d3.event.defaultPrevented) return;
  console.log('clicked');
});

解决方案

Your example works as expected. See updated fiddle : https://jsfiddle.net/thatOneGuy/dd4nujxo/1/

I have put a few added console logs. When you drag this line :

if (d3.event.defaultPrevented) {console.log('return'); return};

Will stop the click event from firing. And when you only click, the dragstart and dragend get fired (as expected), but the drag doesn't. Which is why you put the code to move the circle inside the drag function. The whole thing works as expected :)

这篇关于d3.js:区分拖动/开始/结束和单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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