我正在读亚伦·古斯塔夫森写的一本名为“自适应网页设计”的书,因为我得到了一段我不理解的javascript。在研究过程中,我发现了returning和e.preventDefault之间的区别。我现在也对JavaScript的冒泡效果有了一点了解,并逐渐了解到要停止冒泡,你可以使用e.stopPropagation() (至少在非-ie浏览器中)。
我在玩小提琴,但我就是弄不动它。我认为这可能与冒泡的方式有关(从根到元素再返回?)。
document.body.onclick = function (e) {
alert("Fired a onclick event!");
e.preventDefault();
if ('bubbles' in e) { // all browsers except IE before version 9
if (e.bubbles) {
e.stopPropagation();
alert("The propagation of the event is stopped.");
} else {
alert("The event cannot propagate up the DOM hierarchy.");
}
} else { // Internet Explorer before version 9
// always cancel bubbling
e.cancelBubble = true;
alert("The propagation of the event is stopped.");
}
}这是小提琴:http://jsfiddle.net/MekZii/pmekd/ (固定链接)编辑:我复制-粘贴了错误的链接!现在修好了!
因此,我希望看到的是,当您单击锚点时,div上使用的onclick不会被执行(这不是一个实际案例,只是一个研究案例!)
发布于 2013-07-17 08:25:05
好了,我发现我的第一把小提琴是错的。我发现了另一个确实有效的示例,并展示了stopPropagation()是如何工作的:
var divs = document.getElementsByTagName('div');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function( e ) {
e = e || window.event;
var target = e.target || e.srcElement;
//e.stopPropagation ? e.stopPropagation() : ( e.cancelBubble = true );
if ('bubbles' in e) { // all browsers except IE before version 9
if (e.bubbles) {
e.stopPropagation();
alert("The propagation of the event is stopped.");
} else {
alert("The event cannot propagate up the DOM hierarchy.");
}
} else { // Internet Explorer before version 9
// always cancel bubbling
e.cancelBubble = true;
alert("The propagation of the event is stopped.");
}
this.style.backgroundColor = 'yellow';
alert("target = " + target.className + ", this=" + this.className );
this.style.backgroundColor = '';
}
}http://jsfiddle.net/MekZii/wNGSx/2/
该示例可以在以下链接中找到,其中包含一些阅读材料:http://javascript.info/tutorial/bubbling-and-capturing
发布于 2013-07-16 23:51:15
从单击的元素到document对象,事件都是冒泡的。
div上的任何事件处理程序都将在body上的事件处理程序之前触发(因为body是它在DOM中的祖先)。
当事件到达正文时,要阻止它作用于div已经太晚了。
发布于 2018-07-23 20:34:38
在HTML中要取消从子到父的事件冒泡的地方,请使用下面的代码
event.cancelBubble = true;通过使用这种方式,您可以停止从子元素到父元素进一步向上的事件冒泡。
https://stackoverflow.com/questions/17681176
复制相似问题