我使用jQuery。点击来处理Raphael图形上的鼠标点击事件,同时,我需要处理鼠标拖动事件,鼠标拖动在Raphael中由鼠标下拉,鼠标上拉和鼠标移动组成。

很难区分点击和拖动,因为点击也包含鼠标下拉和鼠标上拉,我怎么能区分鼠标“点击”和鼠标“拖动”然后在Javascript?


当前回答

如果你已经在使用jQuery:

var $body = $('body');
$body.on('mousedown', function (evt) {
  $body.on('mouseup mousemove', function handler(evt) {
    if (evt.type === 'mouseup') {
      // click
    } else {
      // drag
    }
    $body.off('mouseup mousemove', handler);
  });
});

其他回答

有同样的问题,最近在一个树列表中,用户可以点击项目或拖动它,使这个小指针类,并把它放在我的utils.js

function Pointer(threshold = 10) {
  let x = 0;
  let y = 0;

  return {
    start(e) {
     x = e.clientX;
     y = e.clientY;
    },

    isClick(e) {
      const deltaX = Math.abs(e.clientX - x);
      const deltaY = Math.abs(e.clientY - y);
      return deltaX < threshold && deltaY < threshold;
    }
  }
}

下面你可以看到它的工作原理:

function Pointer(threshold = 10) { let x = 0; let y = 0; return { start(e) { x = e.clientX; y = e.clientY; }, isClick(e) { const deltaX = Math.abs(e.clientX - x); const deltaY = Math.abs(e.clientY - y); return deltaX < threshold && deltaY < threshold; } } } const pointer = new Pointer(); window.addEventListener('mousedown', (e) => pointer.start(e)) //window.addEventListener('mousemove', (e) => pointer.last(e)) window.addEventListener('mouseup', (e) => { const operation = pointer.isClick(e) ? "Click" : "Drag" console.log(operation) })

如果只是为了过滤掉拖动的情况,这样做:

var moved = false;
$(selector)
  .mousedown(function() {moved = false;})
  .mousemove(function() {moved = true;})
  .mouseup(function(event) {
    if (!moved) {
        // clicked without moving mouse
    }
  });

这应该能很好地工作。类似于已接受的答案(虽然使用jQuery),但只有当新的鼠标位置与mousedown事件上的位置不同时,isdrag标志才会重置。与公认的答案不同,这适用于最新版本的Chrome,无论鼠标是否移动,鼠标移动都会被触发。

var isDragging = false;
var startingPos = [];
$(".selector")
    .mousedown(function (evt) {
        isDragging = false;
        startingPos = [evt.pageX, evt.pageY];
    })
    .mousemove(function (evt) {
        if (!(evt.pageX === startingPos[0] && evt.pageY === startingPos[1])) {
            isDragging = true;
        }
    })
    .mouseup(function () {
        if (isDragging) {
            console.log("Drag");
        } else {
            console.log("Click");
        }
        isDragging = false;
        startingPos = [];
    });

你也可以在鼠标移动中调整坐标检查,如果你想增加一点公差(即将微小的移动视为点击,而不是拖动)。

如果你想使用Rxjs:

var element = document; Rx.Observable .merge( Rx.Observable.fromEvent(element, 'mousedown').mapTo(0), Rx.Observable.fromEvent(element, 'mousemove').mapTo(1) ) .sample(Rx.Observable.fromEvent(element, 'mouseup')) .subscribe(flag => { console.clear(); console.log(flag ? "drag" : "click"); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://unpkg.com/@reactivex/rxjs@5.4.1/dist/global/Rx.js"></script>

这是@wong2在他的回答中所做的直接克隆,但转换为RxJs。

样本的使用也很有趣。示例操作符将从源(mousedown和mousemove的合并)中获取最新的值,并在内部观察对象(mouseup)发出时发出它。

下面的编码是检测鼠标的移动。

它适用于大多数情况。这也取决于 关于如何将mouseevent处理为单击。 在JavaScript中,检测非常简单。它不关心如何 在鼠标下拉和鼠标上拉之间按住或移动。 Event.detail不会重置为1当你的鼠标移动 鼠标下拉和鼠标上拉。 如果你需要区分点击和长按,你需要 检查事件的差异。时间戳。

// ==== add the code at the begining of your coding ==== let clickStatus = 0; (() => { let screenX, screenY; document.addEventListener('mousedown', (event) => ({screenX, screenY} = event), true); document.addEventListener('mouseup', (event) => (clickStatus = Math.abs(event.screenX - screenX) + Math.abs(event.screenY - screenY) < 3), true); })(); // ==== add the code at the begining of your coding ==== $("#draggable").click(function(event) { if (clickStatus) { console.log(`click event is valid, click count: ${event.detail}`) } else { console.log(`click event is invalid`) } }) <!doctype html> <html lang="en"> <!-- coding example from https://jqueryui.com/draggable/ --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Draggable - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <style> #draggable { width: 150px; height: 150px; padding: 0.5em; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#draggable" ).draggable(); } ); </script> </head> <body> <div id="draggable" class="ui-widget-content"> <p>Drag me around</p> </div> </body> </html>