我有一個用于單擊或長按的購物車圖示。如果用戶點擊它,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();
}
});
}
}
問題是如何防止長按后的點擊事件?問題是當購物車串列出現時,該產品已添加到購物車!我希望長按時不會觸發點擊。
uj5u.com熱心網友回復:
您可以通過掛鉤到事件捕獲階段來取消單擊事件的傳播。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/480857.html
標籤:javascript 点击 设置超时 长按
上一篇:如何在回圈內設定陣列的值?
