[英]how to implement longpress and click sepereate event in 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.