我有一个表行,当我点击它时,我想要有两个函数。通过长按,我想选择行(添加".active_row“类),通过正常单击,我想打开此数据集的详细信息站点。
对于长按检测,我使用了第三方脚本here。只需稍加修改,它就可以为我工作,并正确地触发事件"long-press“。但现在的问题是,如果我松开鼠标按钮,鼠标向上和单击事件也会被触发……
我比较了自动触发后长按点击和手动触发点击的事件详细信息,它们是相同的。所以我不能用这个来区分它。
有什么想法吗?
第三方脚本在鼠标按钮按下500ms后触发自定义的长按事件。它使用了mousedown事件和一个简单的超时函数:
this.dispatchEvent(new CustomEvent('long-press', { bubbles: true, cancelable: true }));发布于 2020-06-06 00:42:52
你可以这样做:
// 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中的代码片段就不工作了)
https://stackoverflow.com/questions/56802461
复制相似问题