对于移动设备,没有像右键单击的操作 - 所以我想要为此处理长按操作。jQuery:防止点击事件被长时间点击后触发(移动)
我还需要一个正常的“点击”事件。
对于长按处理我找到了一个解决方案,但是当我添加一个onClick监听器时,即使我只想要长按事件被触发,onClick也会被触发。
如何在longTap事件触发时防止点击事件?
这里是代码+例如:
var c = console.log.bind(console);
(function() {
$.fn.longTap = function(options) {
options = $.extend({
delay: 1000,
onRelease: null
}, options);
var eventType = {
mousedown: 'ontouchstart' in window ? 'touchstart' : 'mousedown',
mouseup: 'ontouchend' in window ? 'touchend' : 'mouseup'
};
return this.each(function() {
$(this).on(eventType.mousedown + '.longtap', function() {
$(this).data('touchstart', +new Date);
})
.on(eventType.mouseup + '.longtap', function(e) {
var now = +new Date,
than = $(this).data('touchstart');
now - than >= options.delay && options.onRelease && options.onRelease.call(this, e);
});
});
};
})(jQuery);
$('.long-tap').longTap({
delay: 1000, // really long tap
onRelease: function(e) {
c($(this).position(), e);
e.stopImmediatePropagation();
e.preventDefault();
alert('show context menu or something else:');
}
});
$('.long-tap').click(function(){
\t alert("click");
})
.test {
width: 200px;
height: 100px;
background-color: #DDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test long-tap"></div>
有很多插件可以处理它,为什么要发明轮子? – Tomer