【问题标题】:Prevent click action on all elements inside body防止对正文内的所有元素进行单击操作
【发布时间】:2015-03-13 17:51:08
【问题描述】:

我正在编写一个 WYSWIG 内联编辑器,除了编辑器菜单元素之外,所有元素都是可编辑的。

JS 代码

$(function() {
    $("body").on("mousedown", function(e) {

        if($(e).target().is(".ignore")) {
            return;
        }

        //I hope it will stop the event to bubble up
        e.preventDefault();
        e.stopPropagation();
    });

    $("body").on("click", function(e) {
          e.preventDefault();
          e.stopPropagation();
    });
});

HTML

<body>
<a href="http://google">Google</a>
<button onclick="window.location.url='https://www.amazon.com'">Amazon</button>
<button onclick="alert('Ignore unbind')" class="ignore">Ignore</button>

<iframe src="http://w3schools.org" />

演示

http://jsfiddle.net/e7gbm557/2/

问题

在上面的一个中,按钮元素的点击事件被阻止,但如果你点击 iframe 内的锚标记,它会将我带到链接 url。

不仅对于 iframe 中的锚标记,它也适用于其他一些元素。

什么是防止对正文中除某些元素之外的所有元素进行点击操作的正确方法?

【问题讨论】:

  • 您无法阻止加载到 iframe 的第三方页面上的事件。您可以在 iframe 上创建一个透明的封面元素,这可能会解决问题。
  • @Teemu 如果正文中的元素绑定点击事件并调用 event.stopPropagation() 会发生什么,我的父点击事件绑定将不会被调用。我说的对吗?

标签: javascript jquery html iframe


【解决方案1】:

您需要处理click 事件,而不是mousedown 事件:

$("body").on("click", function(e) {
    //I hope it will stop the event to bubble up
    e.preventDefault();
    e.stopPropagation();
});

Working JSFiddle demo.

此外,您的第一个 button 元素的 onclick 无论如何都没有真正做任何事情。你的e.preventDefault() 没有解决这个问题,因为没有什么可以阻止的。默认情况下没有分配给window.locationurl 属性,您只需将其添加到window.location。这应该只是:

<button onclick="window.location='https://www.amazon.com'">Amazon</button>

【讨论】:

  • 非常感谢 James,如果子元素绑定了 click 事件并调用 event.stopPropagation(),它将无法到达父绑定。如果我错了,请纠正我。
猜你喜欢
  • 2016-11-27
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多