且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

禁用页面上的所有点击事件(javascript)

更新时间:2023-12-03 08:58:58

如果目标是禁用点击整个页面然后你可以做这样的事情

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

addEventListener中的true参数将确保在事件捕获阶段执行处理程序即,首先在文档上捕获任何元素的点击,并且在侦听者之前首先执行文档的点击事件的监听器以用于任何其他元素。这里的技巧是阻止事件进一步传播到下面的元素,从而结束调度过程,以确保事件没有到达目标。

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

以这种方式修改的处理程序将仅禁用具有类class_name的元素的点击次数。

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