如果“鼠标移动"怎么办?和“点击"事件同时触发? [英] What to do if "mousemove" and "click" events fire simultaneously?

查看:66
本文介绍了如果“鼠标移动"怎么办?和“点击"事件同时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$("div").on({鼠标移动:功能(e){console.log("移动");},点击:功能(e){console.log("点击");}});

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

<代码>>>...>>点击>>移动

演示: http://jsfiddle.net/gKqVt/>

请注意,mousedownmouseup 事件在相同的场景下工作.

我在 SO 上看到了很多关于同一问题的问题,但没有一个(在我的搜索中)给出了如何触发 click 事件 only 的直接想法.

解决方案

这种行为很奇怪,而且似乎并不普遍发生(对我来说在 Chrome/IE 中发生,但在 FFX 中没有发生).我想你还没有得到一个直接的答案,因为真的没有.

鼠标可能会因点击动作而轻微移动,但可能并非如此.可能只是浏览器的怪癖.这些甚至似乎不是同一个事件,因为 click 中的 stopImmediatePropagation 不会阻止 mousemove 触发.如果您聚焦元素并点击键盘按钮,它实际上会触发click 并且only click.

既然这太古怪了,似乎唯一的办法就是时间.尽管这很麻烦,但我确实注意到 click 发生在 mousemove 之前一毫秒,因此您可以通过比较点击来接近时间戳 + 2(或 10):

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

http://jsfiddle.net/gKqVt/3/

不过,这是非常具体的.您应该考虑不要在 mousemove 上立即发生行为,因为它非常频繁.

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");
    }
});

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

DEMO: http://jsfiddle.net/gKqVt/

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

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.

解决方案

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.

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.

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) {

http://jsfiddle.net/gKqVt/3/

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

这篇关于如果“鼠标移动"怎么办?和“点击"事件同时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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