簡體   English   中英

長按也會觸發“點擊”和“鼠標向上”

[英]Long-Press also fires "click" and "mouseup"

我有一個表格行,當我點擊它時我想有兩個功能。 長按我想選擇該行(添加一個“.active_row”類),然后正常單擊我想打開該數據集的詳細信息站點。

對於長按檢測,我使用此處找到的第三方腳本。 只需稍加修改,它就適用於我並正確觸發事件“長按”。 但現在的問題是,如果我釋放鼠標按鈕,事件 mouseup 和 click 也會被觸發......

我比較了長按點擊后自動觸發的事件詳細信息和手動觸發的點擊,它們是相同的。 所以我不能用這個來區分它。

有任何想法嗎?

在鼠標按鈕按下 500 毫秒后,第三方腳本會使用此觸發自定義長按事件。 它使用事件 mousedown 和一個簡單的超時功能:

this.dispatchEvent(new CustomEvent('long-press', { bubbles: true, cancelable: true }));

你可以這樣做:

 // listen for long-press events document.addEventListener('long-press', function(e) { e.target.classList.toggle('selected'); e.target.setAttribute('data-long-pressed', true); }); // listen for long-press events document.addEventListener('click', function(e) { if ( e.target.getAttribute('data-long-pressed') ) { e.preventDefault() ; e.stopPropagation() ; e.target.removeAttribute('data-long-pressed'); } // What you whant here }, true); /*! * long-press.js * Pure JavaScript long-press event * https://github.com/john-doherty/long-press * @author John Doherty <www.johndoherty.info> * @license MIT */ !function(t,e){"use strict";function n(){this.dispatchEvent(new CustomEvent("long-press",{bubbles:!0,cancelable:!0})),clearTimeout(o),console&&console.log&&console.log("long-press fired on "+this.outerHTML)}var o=null,s="ontouchstart"in t||navigator.MaxTouchPoints>0||navigator.msMaxTouchPoints>0,u=s?"touchstart":"mousedown",a=s?"touchcancel":"mouseout",i=s?"touchend":"mouseup";"initCustomEvent"in e.createEvent("CustomEvent")&&(t.CustomEvent=function(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var o=e.createEvent("CustomEvent");return o.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),o},t.CustomEvent.prototype=t.Event.prototype),e.addEventListener(u,function(t){var e=t.target,s=parseInt(e.getAttribute("data-long-press-delay")||"1500",10);o=setTimeout(n.bind(e),s)}),e.addEventListener(i,function(t){clearTimeout(o)}),e.addEventListener(a,function(t){clearTimeout(o)})}(this,document);
 .dock-item { font-size: 14px; font-family: arial; display: inline-block; margin: 10px; padding: 10px; border: 1px solid #ccc; cursor: pointer; width: 70px; height: 70px; border-radius: 3px; text-align: center; user-select: none; } .selected{ background-color: red; }
 <a class="dock-item" data-long-press-delay="500" href='/' target='_blank'>Press and hold me for .5s</a> <a class="dock-item" href='/' target='_blank'>Press and hold me for 1.5s</a> <a class="dock-item" data-long-press-delay="5000" href='/' target='_blank'>Press and hold me for 5s</a>

這里有一個小提琴: https : //jsfiddle.net/2q7430sy/ (因為單擊在stackoverflow代碼段中不起作用)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM