Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

disable all click events on page (javascript)

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

I thought I could do document.onclick = function() { return false; }; ...etc, but that's not working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...