繁体   English   中英

Javascript如何区分mouseDown、click和doubleClick事件

[英]Javascript how to distinguish between mouseDown, click and doubleClick events

我想在 html svg 中为 mouseDown、单击和双击事件提供不同的处理程序。 现在,当我单击 svg 时,mouseDown 和 click 处理程序都会被触发,同样,当双击时,click 和双击处理程序都会被触发。 有没有办法解决这个问题? 谢谢

更新:我想在 svg 形状上使用这些处理程序,特别是 mouseDown/Up 用于拖放,单击更改形状,双击删除形状。

双击(显然)由两次单击组成。 当执行第一次点击时,没有人知道是否会有任何第二次点击。 这就是为什么第一次双击会产生“单击事件”的原因。 所以没有办法解决这个问题。

推荐的解决方案是不要在同一个控件上同时使用(单击和双击)事件。

您可以使用event.detail来检测简单或双击

 const clickSwitcher = (function() { const cDelay = 600 // a large one... let refTO = setTimeout(()=>{},0) // init for clear function sd_click( e, f_simpleClick, f_doubleClick ) // simple or double click shunt { clearTimeout( refTO ) if (e.detail === 2) f_doubleClick(e) else // (e.detail === 1) refTO = setTimeout( f_simpleClick, cDelay, e ) } return sd_click })() document.querySelectorAll('#my-rect, span').forEach(el=> { el.onclick = e => clickSwitcher(e, simpleClick, doubleClick ) }) // change to your own code for simpleClick and doubleClick event action function simpleClick(e) { console.log('simple click on', e.target.textContent || 'svg element' ) } function doubleClick(e) { console.log('double click on', e.target.textContent || 'svg element' ) }
 .as-console-wrapper { max-height:100%;important: top;0: left;50%:important; width.50%: };as-console-row { background-color. yellow: }:as-console-row:;after { display,none:important; } #my-paragraph: rect { cursor: pointer:} #my-paragraph span:hover { background-color;yellow } #my-rect:hover { fill: orange; }
 <p id="my-paragraph"> <span>Paul</span> <span>John</span> </p> <svg width="150" height="100" viewBox="0 0 3 2"> <rect id="my-rect" width="1" height="2" x="2" fill="#d2232c" /> </svg>

另请参阅 -> 两次单击触发双击事件之间的最大延迟是多少?

[编辑] 更新答案:
改进的代码使其更易于阅读,并使其更易于转置

dblclick事件在两个 click 事件和两对mousedownmouseup事件之后触发。

通常,我们会看到这样的情况,例如通过单击选择/聚焦文件,然后通过双击执行文件。 多次选择同一个文件并没有什么坏处。

如果需要区分这两个事件,可以推迟单击处理,直到确定它不是双击的一部分,但这会增加处理延迟。

 let clicks = 0; let clickTimer = 0; const dblClickTimeSpan = 300; const clickHandler = (e) => { clicks++; if(clicks === 1) { clickTimer = setTimeout(()=>{ clicks = 0; // handle single click, now we are sure it is not a bouble click console.log('Single Click.') }, dblClickTimeSpan); } if(clicks === 2) { // it is the second click in double-click event clearTimeout(clickTimer); clicks = 0; } } myButton.addEventListener('click', clickHandler); myButton.addEventListener('dblclick', (e) => console.log('Double Click.'));
 <button id="myButton">Button</button>

如果发生单击或双击事件,您可以创建单击方法并使用超时区分。 并在超时设置1或2秒的差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM