本文介绍了如果“mousemove”和“点击”事件同时发火?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道Chrome浏览器是否只是问题(现在无法检查),但是让我们尝试以下代码段,我们将两个事件绑定到一些元素:

I don't know whether it is only Chrome problem (can't check now), however let's try the following piece of code, where we bind two events to some element:

$("div").on({
    mousemove: function(e) {
        console.log("move");
    },
    click: function(e) {
        console.log("click");
    }
});

如果我们尝试点击元素,我们会发现由于某种原因 mousemove 事件在点击后立即触发,所以在控制台中我们有:

If we try to click the element, we'll find that for some reason mousemove event fires immediately after click, so in console we have:

>> ...
>> click
>> move

演示:

请注意, mousedown mouseup 事件在同一情况下工作。

Note, that mousedown and mouseup events work by the same scenario.

我在SO上看到很多问题关于同样的问题,但没有(在我的搜索中)给出了一个简单的想法,为了触发点击事件 。 p>

I saw many questions on SO about the same problem, but none (in my search) gave the straightforward idea what to do in order to fire the click event only.

推荐答案

这种行为是奇怪的,它似乎并不普遍(在Chrome / IE中为我而不是FFX) 。我认为你没有得到一个直接的答案,因为没有一个真正的。

This behavior is odd, and it doesn't seem to occur universally (happens in Chrome/IE for me, but not FFX). I think you haven't gotten a straight answer because there isn't one really.

可能鼠标点击动作非常轻微,但这可能不是。可能只是一个浏览器的怪癖。这些甚至似乎不是相同的事件,因为 stopImmediatePropagation 单击不停止 mousemove 从点燃。如果您重点关注元素并点击键盘按钮,它将实际触发单击 单击

It's possible that the mouse is moved very slightly by the click action, but that's probably not it. Could just be a browser quirk. These don't even seem to be the same event since stopImmediatePropagation in click doesn't stop mousemove from firing. If you focus the element and hit a keyboard button, it will actually trigger click and only click.

由于这是如此古怪,似乎处理它的唯一方法是时间。与此一样,我确实注意到点击 mousemove ,所以你可以通过比较点击时间戳+2(或10)来获得关闭:

Since this is so quirky, it seems like the only way to deal with it is times. As much of a kludge as this is, I do notice that click happens one millisecond before mousemove, so you could get close by comparing the click timestamp + 2 (or 10):

mousemove: function(e) {
    if ($(this).data('lastClick') + 10 < e.timeStamp) {

尽管如此,这是非常具体的。你应该考虑不要在mousemove上立即出现行为,因为它很频繁。

This is very specific, though. You should consider not having behavior that occurs immediately on mousemove since it's so frequent.

这篇关于如果“mousemove”和“点击”事件同时发火?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:20