如何在 javascript 中实现长按和单击单独的事件?

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();
            }
        });
    }
}

问题是长按后如何防止点击事件? 问题是当购物车列表出现时,产品已添加到购物车! 我希望在长按时不触发点击。

您可以通过 hooking into the event capture phase 取消传播点击事件。

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>