disable all click events on page (javascript)

后端 未结 8 1798
孤城傲影
孤城傲影 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:46

    If the objective is to disable click on the whole page then you can do something like this

    document.addEventListener("click",handler,true);
    
    function handler(e){
        e.stopPropagation();
        e.preventDefault();
    }
    

    true argument in addEventListener would ensure that the handler is executed on the event capturing phase i.e a click on any element would first be captured on the document and the listener for document's click event would be executed first before listener for any other element. The trick here is to stop the event from further propagation to the elements below thus ending the dispatch process to make sure that the event doesn't reach the target.

    Also you need to stop default behavior associated with event target elements explicitly as they would be executed by default after the dispatch process has finished even if the event was stopped propagating further from above

    It can be further modified to use selectively.

    function handler(e){
    if(e.target.className=="class_name"){
    e.stopPropagation();
    e.preventDefault();
    }
    

    handler modified this way would disable clicks only on elements with class "class_name".

    function handler(e){
        if(e.target.className!=="class_name")
        e.stopPropagation()
    }
    

    this would enable clicks only on elements with class "class_name". Hope this helped :)

    0 讨论(0)
  • 2020-12-13 15:46

    If you want absolutely nothing draggable/clickable, disabling typing in input fields etc, I'd consider showing a absolutely positioned transparent div over the entire page, so that every click will be on the div, which will do nothing. That will grant you swift and neat switching on and off of this click-disabler, without having to register heaps of listeners

    0 讨论(0)
提交回复
热议问题