如何在javascript中实现长按和点击分离事件?



我有一个购物车图标点击或长按。如果用户单击它,ajax将产品添加到购物车中,当用户按住鼠标时,购物车列表出现。

下面是js代码:
const shopping = document.getElementById('shopping');
shopping.addEventListener('mousedown' , function() {
pressTimer = window.setTimeout(longpressed,1000);
});
shopping.addEventListener('mouseup' , function() {
clearTimeout(pressTimer);
});
shopping.addEventListener('click' , function(e) {
console.log('click');
$.ajax({
url: "{{route('user.cart.add' , $product->id)}}",
method: 'get',
data: {
_token: '{{ csrf_token() }}',
id: '{!! $product->id !!}'
},
success: function(quantity){
$("#lblCartCount").html(quantity);
}
});
});
function longpressed() {
console.log('longpress');
if(!$('#showFactor').is(':empty')){
$('#showFactor').html('');
$('#showFactor').hide();
}else{
$.ajax({
url: "{{route('user.cart.index')}}",
method: 'get',
data: {
_token: '{{ csrf_token() }}',
},
success: function(response){
$('#showFactor').html(response);
$('#showFactor').show();
}
});
}
}

问题是如何防止长按后的点击事件?问题是当购物车列表出现时,产品已经添加到购物车了!我想让点击在长按时不开火。

您可以通过挂钩到事件捕获阶段来取消单击事件的传播。

const shopping = document.getElementById('shopping');
shopping.addEventListener('mousedown' , function() {
pressTimer = window.setTimeout(longpressed,1000);
});
shopping.addEventListener('mouseup' , function(e) {
clearTimeout(pressTimer);
});
shopping.addEventListener('click' , function(e) {
console.log('click');
});
function longpressed() {
console.log('longpress');

window.addEventListener(
'click',
captureClick,
true // <-- This registers this listener for the capture
//     phase instead of the bubbling phase!
);
}
function captureClick(e) {
e.stopPropagation(); // Stop the click from being propagated.
window.removeEventListener('click', captureClick, true); // cleanup
}
<button type="button" id="shopping">
Shopping cart
</button>

最新更新