如何区分点击+拖动与双击+拖动

时间:2018-09-12 19:53:06

标签: javascript

我的项目需要区分单击,双击,单击+拖动和双击+拖动。现在我已经可以区分前3个事件,但不知道如何检测双击和拖动。有想法吗?

var holdStarter = null;
var holdDelay = 500;
var holdActive = false;

function onMouseDownEssence() {

  holdStarter = setTimeout(function() {
    holdStarter = null;
    holdActive = true;

    console.log("click and dragging ");

  }, holdDelay);

}


function onMouseUpEssence(el) {
  if (holdStarter) {
    clearTimeout(holdStarter);

    if (el.getAttribute("data-dblclick") == null) {
      el.setAttribute("data-dblclick", 1);
      setTimeout(
        function() {
          if (el.getAttribute("data-dblclick") == 1) {
            console.log("single clicked ");
          }
          el.removeAttribute("data-dblclick");
        }, 300);
    } else {
      el.removeAttribute("data-dblclick");

      console.log("double clicked ");
    }
  } else if (holdActive) {
    console.log("click and drag done");
    holdActive = false;

  }

}

1 个答案:

答案 0 :(得分:2)

我删除了一个超时,并添加了一个变量dragTarget来跟踪所拖动的元素。

var holdStarter = null;
var dblDelay = 300;
var holdDelay = 500;
var holdActive = false;
var dragTarget = null;
var dbl = "data-dblclick";
window.addEventListener('mousedown',function(e){
  dragTarget = e.target;
  holdStarter = new Date().valueOf();
});
window.addEventListener('mouseup',function(e){
  var el = e.target;
  var holdActive = (new Date().valueOf() - holdStarter) > holdDelay;
  if (holdActive) {
    if (el.getAttribute(dbl) == null) {
      console.log("drag done");
    } else {
      console.log("double drag done");
      el.removeAttribute(dbl);
    }
    holdActive = false;
  } else if (el.getAttribute(dbl) == null) {
    el.setAttribute(dbl, 1);
    setTimeout(function() {
      if (el.getAttribute(dbl) == 1 && !dragTarget) {
        console.log("single clicked ");
        el.removeAttribute(dbl);
      }
    }, dblDelay);
  } else {
    console.log("double clicked");
    el.removeAttribute(dbl);
  }
  dragTarget = null;
});