-
stopPropagation 方法
- 注意点: stopPropagation 方法只支持高级浏览器
// 1.拿到需要操作的元素 let oFDiv = document.getElementById("father"); let oSDiv = document.getElementById("son"); // 2.注册事件监听 oFDiv.onclick = function () { console.log("father"); }; oSDiv.onclick = function (event) { event = event || window.event; // 注意点: stopPropagation方法只支持高级浏览器 event.stopPropagation(); console.log("son"); // 只会执行son };
-
cancelBubble 方法
- 低级浏览器的写法
// 1.拿到需要操作的元素 let oFDiv = document.getElementById("father"); let oSDiv = document.getElementById("son"); // 2.注册事件监听 oFDiv.onclick = function () { console.log("father"); }; oSDiv.onclick = function (event) { event = event || window.event; // 低级浏览器的写法 event.cancelBubble = true; console.log("son"); };
-
兼容性写法
// 1.拿到需要操作的元素 let oFDiv = document.getElementById("father"); let oSDiv = document.getElementById("son"); // 2.注册事件监听 oFDiv.onclick = function () { console.log("father"); }; oSDiv.onclick = function (event) { event = event || window.event; // 兼容性写法 if (event.cancelBubble){ event.cancelBubble = true; } else { event.stopPropagation(); } console.log("son"); };
网友评论