disable all click events on page (javascript)

后端 未结 8 1821
孤城傲影
孤城傲影 2020-12-13 15:11

Whats the easiest way to temporarily disable all mouse click/drag etc events through javascript?

I thought I could do document.onclick = function() { return fa

8条回答
  •  生来不讨喜
    2020-12-13 15:44

    Dynamically disable all clicks on page

    let freezeClic = false; // just modify that variable to disable all clics events
    
    document.addEventListener("click", e => {
        if (freezeClic) {
            e.stopPropagation();
            e.preventDefault();
        }
    }, true);
    
    

    I often use it while loading or to avoid user to accidentally clic twice on an action button. Simple and performance friendly :)

    Please check this working example

    Alternative CSS way

    Another one that I really like because of the visual feedback the user got:

    /* style.css */
    .loading {
        cursor: wait; /* busy cursor feedback */
    }
    
    .loading * {
        /* disable all mouse events on subElements */
        pointer-events: none; 
    }
    

    Then you just need to do:

    $('#my-item').addClass('loading');
    await myAsyncFunction() // wait until the function complete
    $('#my-item').removeClass('loading');
    

提交回复
热议问题