禁用页面上的所有点击事件(javascript) [英] disable all click events on page (javascript)

查看:164
本文介绍了禁用页面上的所有点击事件(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过javascript暂时禁用所有鼠标点击/拖动等事件的最简单方法是什么?

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

我以为我可以做 document.onclick = function(){return false; }; ...等,但这不起作用。

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

推荐答案

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

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

这篇关于禁用页面上的所有点击事件(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆