单击内部元素并将鼠标拖动到外部

Clicking inside element and dragging mouse outside it

我敢肯定有人遇到过这样的问题,但不幸的是我找不到答案。

window.onload = function (e) {
    var foo = document.getElementById('foo');
    foo.addEventListener('click', function(e) {
      e.stopPropagation();
      e.preventDefault();
      alert('foo');
    });
    document.body.addEventListener('click', function(e) {
      alert('body');
    });
};
#foo {
  width: 200px;
  height: 200px;
  background-color: red;
  cursor: pointer;
}
body,
html {
  width: 100%;
  height: 100%;
}
<div id="foo">Click me</div>

请参阅 jsfiddle 和 我将逐步描述我的问题:

1) 单击红色 div 2) 不要松开鼠标拖到外面

如您所见,正文点击功能已触发。这就是我想要禁用的。我想检测用户是否在 div 内部单击,如果 he/she 拖到它外面,则什么都不会发生!

使用:

e.stopImmediatePropagation();

Prevents other listeners of the same event from being called.

来源 MDN:https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation

window.onload = function (e) {
    var foo = document.getElementById('foo');
    foo.addEventListener('click', function(e) {
      e.stopImmediatePropagation();
      e.preventDefault();
      alert('foo');
    });
    document.body.addEventListener('click', function(e) {
      alert('body');
    });
};
#foo {
  width: 200px;
  height: 200px;
  background-color: red;
  cursor: pointer;
}
body,
html {
  width: 100%;
  height: 100%;
}
<div id="foo">Click me</div>

看起来 Firefox 是唯一一个在光标离开原始元素时不触发点击的浏览器。在与 webkit 相关的浏览器上,没有原始 mousedown 的痕迹,但所有事件数据都基于这样的事实,就好像在 body 上触发了完整的点击一样。所以没办法根据点击本身来区分。可能有一些解决方法,但这里有一个 - 检查是否有任何点击来自元素上的 mousedown :

window.addEventListener('load', function() {

var foo = document.getElementById('foo'), fromfoo,
origin  = document.getElementById('origin');

foo.addEventListener('mousedown', function(e) {

    e.stopPropagation();

    fromfoo = true;
});

document.body.addEventListener('mousedown', function() {

    fromfoo = false;
});

foo.addEventListener('mouseup', function(e) {

    e.stopPropagation();

    if (fromfoo) origin.innerHTML = 'foo';
});

document.body.addEventListener('mouseup', function() {

    if (fromfoo) origin.innerHTML = 'different';
    else origin.innerHTML = 'body';
});
});
html, body {
  width:100%;
  height:100%;
  margin: 0;
}

#origin {
  float: right;
  margin: 50px 100px;
}

#foo {
  width:200px;
  height:200px;
  background-color: red;
  cursor:pointer;
}
<div id="origin"></div>
<div id="foo">Click me</div>

一个很好的解决方法,但部分原因是为了使其与 Mozilla 反向兼容。

编辑 - 很奇怪,Microsoft documentation 是这么说的:

For example, if the user clicks the mouse on the object but moves the mouse pointer away from the object before releasing, no onclick event occurs.

但似乎根本不是这样。


更新 - 经过大量搜索后也找到了这份报告:

https://code.google.com/p/chromium/issues/detail?id=484655

所以这似乎至少是错误行为或对 W3 规范的误解。显然是 IE 的一个已知问题,最近出现了 Chrome。 This question from 2013 about IE only looks related as well。有人发布了一个可能仍然有用的小插件:

Internet Explorer leaks click event after adding an overlay in a jQuery mousedown handler