Javascript 防止对主体内的所有图元执行单击操作
我正在写一个WYSWIG内联编辑器,除了编辑器菜单元素之外,所有元素都是可编辑的 JS代码Javascript 防止对主体内的所有图元执行单击操作,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,我正在写一个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.preventD
$(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" />
亚马逊
忽略
演示
问题
在上面的一个例子中,button元素阻止了click事件,但是如果您单击iframe内的锚标记,它会将我带到链接url中
不仅对于iframe中的锚定标记,其他一些元素也会发生这种情况
什么是防止对主体内除某些元素以外的所有元素执行单击操作的正确方法?您需要处理
单击事件,而不是鼠标向下事件:
$("body").on("click", function(e) {
//I hope it will stop the event to bubble up
e.preventDefault();
e.stopPropagation();
});
此外,您的第一个按钮
元素的onclick
实际上并没有做任何事情。你的e.preventDefault()
无法解决这个问题,因为根本没有什么可以阻止的。默认情况下,没有url
属性分配给window.location
,您只需将其添加到window.location
。这应该是:
<button onclick="window.location='https://www.amazon.com'">Amazon</button>
Amazon
您无法阻止将第三方页面上的事件加载到iframe中。您可以在iframe上创建一个透明的cover元素,这可能会解决这个问题。@Teemu如果主体内的元素绑定click事件并调用event,会发生什么情况。stopPropagation(),则不会调用父click事件绑定。我说得对吗?非常感谢James,如果子元素绑定click事件并调用event.stopPropagation(),它将不会到达父绑定。如果我错了,请纠正我。