如何防止在 mousemove 函数中弹出多个警报、确认或提示?

How do I prevent more than one alert, confirm or prompt popping up in a mousemove function?

我的 JS 代码是这样的:

当您快速移动鼠标时,会出现比警告框更多的情况。所以我尝试在 mousemove 的回调函数中添加一些变量。但是问题还是存在,怎么办?

var has_alert=false;
$('div').on('mousemove',function(){
  if(has_alert) return;
  has_alert=true;
  alert(2)
  has_alert=false;
})
body {background:red}
div {background:white; width:500px;height:500px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>test content</div>

问题在于alertconfirmprompt。这些都产生一个模态window,它暂时禁止处理其他挂起的(mousemove)事件。到处理第二个事件时,第一个事件处理程序已经完成,对话框已关闭,并且 has_alert 已返回 false。似乎无法区分 对话框打开之前触发的事件与 对话框关闭之后立即触发的事件之间的区别。

一种解决方案是 has_alert 的延迟重置:

var has_alert=false;
$('div').on('mousemove',function(){
  if(has_alert) return;
  has_alert=true;
  alert(2)
  window.setTimeout(function() { has_alert=false; }, 20);
})
body {background:red}
div {background:white; width:500px;height:500px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body>

<div>test content</div>
</body>

另一种解决方案是完全放弃 alertconfirmprompt,并改用基于 HTML 的对话框。恕我直言,这是一个你不会后悔的设计决定 运行.