暂时禁用所有onclick事件并将它们绑定回来

Temporarily disable all onclick events and bind them back

本文关键字:回来 绑定 事件 onclick      更新时间:2023-09-26

如何禁用页面上的所有onclick事件,绑定我的自定义函数,并在执行后启用所有先前的事件?

我正在构建一个bookmarklet,它应该在任何已经加载的页面上工作,我使用jQuery来处理我的自定义逻辑(页面在加载后被jQuery化)。请注意,我无法控制绑定哪些事件以及何时绑定。

目前我发现的最好的稳定解决方案是取消绑定事件,通过自定义函数绑定防止默认操作,然后重新加载页面。这是可行的,但是我想避免重新加载。部分解决方法是重新加载页面并滚动到以前的位置(如何实现此效果?)。一些可能的解决方案是使用iframe,但我宁愿避免这种情况。

在所有的div元素上放置div-element更容易…就像

CSS

.noclick {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999; /* or maybe higher */
    background-color: transparent;
}
jQuery

jQuery(document).ready(function() {
    jQuery('body').append('<div class="noclick" />');
});

我见过的一个很好的方法,我自己也做过,那就是使用模态'蒙版'覆盖。

覆盖整个页面的灰色透明蒙版,除了你正在与之交互的元素,例如。模态弹出窗口

另一种方法是使用jQuery的BlockUI插件

你可以将onclick重新分配给另一个属性,然后重写它。

一个元素的例子

var btn = document.getElementById("button");
btn._onclick = btn.onclick;
btn.onclick = function(){ return false; };

,当你想把它转移回原始事件

var btn = document.getElementById("button");
if (btn._onclick) {
    btn.onclick = btn._onclick;
    btn._onclick = null;
}

这取决于你的onclick事件是否依赖于被点击的元素(即是否需要知道哪个元素被点击了):

如果它是独立的,那么你可以只添加一个事件处理程序到body元素或其他父元素(因为父事件首先被调用,然后是子事件,这是你想要的):

$('body').click(function() { /* your code here */});

如果它依赖于元素,那么你可以访问之前的onclick事件代码,该代码已经在被点击的元素的'click'属性中注册,所以像这样(可能是更具体的选择器):

$('body *').each(function() {
  var previousClick = this.click;
  this.click = null; // remove previous
  $(this).click(function() { /* your code here */});
  $(this).click(function() { previousClick();}); // run the code that was already there.
})

一些修改算法的答案。这个想法是用透明元素"覆盖"链接。您可以使用伪元素(例如:在之后)。

防止"tab键"设置tabindex:

<a href="..." tabindex="-1">

用"disabled"类标记链接:

$('a').on('click', function(){ $(this).addClass('disabled') })

添加css:

a.disabled:after { position: absolute; content: ""; display: block; background: white; opacity: 0.5; // optional z-index: 999; left: 0; top: 0; bottom: 0; right: 0; }

$('a').on('click', function(){ $(this).addClass('disabled') });
a.disabled:after {
    position: absolute;
    content: "";
    display: block;
    background: white;
    opacity: 0.5; // optional 
    z-index: 999;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a hreh="#" tabindex="-1">The Link</a>