【问题标题】:click event not firing when moving mouse on an image在图像上移动鼠标时单击事件未触发
【发布时间】:2017-10-17 22:37:07
【问题描述】:

我遇到过这个问题,我在图像上有一个 onclick 事件,但是当鼠标在 mousedown 和 mouseup 事件之间移动时,它不会被触发。

我有一张图片,我想在其中进行 onlick 事件。我也不希望任何人拖动/选择或打开上下文菜单。 现在我发现,在触摸屏上,有 50% 的人点击某个图像时发生的情况是,当他们按下图像时,他们的手指会移动。所以 mousedown 和 mouseup 事件之间存在微小的差异。但是当他们这样做时,不会触发 click 事件(至少在 chrome 中)。也不会触发 onmouseup-event。

看看这个:https://fiddle.jshell.net/08pbjfq2/1/

单击图像将显示警报和鼠标向上和向下事件,但是当您单击并使用鼠标移动超过 3 个像素左右时,不会触发单击和鼠标向上事件。看起来,如果您单击然后将鼠标移动 1 个像素,则 mousedown 事件和 onclick 事件会被触发,但不会触发 mouseup 事件。这是一个错误还是我在这里遗漏了什么?

【问题讨论】:

  • stackoverflow.com/questions/13358292/… 在这里你会得到答案。
  • onmouseUp="document.getElementById('mouseDown').style.display = 'block';" 可能是您的问题,当您将 ID 更改为正确的 'mouseUp' 时,它可以正常工作!

标签: javascript html google-chrome onclick


【解决方案1】:

这看起来像一个 chrome 错误。

发生这种情况是因为您阻止了拖动事件,该事件不应链接到单击事件。

解决方法:

你可以通过在chrome中设置draggable="false"属性来防止拖拽,但是FF不支持。因此,要支持 FF,您仍然必须阻止该事件。

var img1 = document.images[0];
img1.ondragstart = e => e.preventDefault();
img1.onclick = e =>  console.log('clicked first');

// to show that this is the problem in chrome :
var img2 = document.images[1];
img2.ondragstart = e => e.preventDefault();
img2.onclick = e =>  console.log('clicked second');
/* CSS can prevent selection */
img{
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  }
<img draggable="false" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTS0G-xT5r9xjdGAHlvZk2wdZVhyP6LOpOJE7PyNLXdUCs0pG-gqA" 
 />
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTS0G-xT5r9xjdGAHlvZk2wdZVhyP6LOpOJE7PyNLXdUCs0pG-gqA" 
 />

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多