发表于: 2019-04-20 10:32:52

1 596


今天完成的事情:

1做复盘


明天计划的事情:

2继续做复盘


收获:

阻止冒泡事件和默认事件

//方法一: event.stopPropagation();
方法一js和JQ都行
//方法二: event.preventDefault();
方法二js和JQ都行
//方法三: stopImmediatePropagation();
方法三是阻止后续的冒泡事件
//方法四: return false;
方法四是阻止JS的默认事件和JQ的默认和冒泡事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#parent {
margin: 35vh auto;
width: 200px;
height: 200px;
text-align: center;
line-height: 3;
background: green;
}
#child {
width: 100px;
height: 100px;
margin: 0 auto;
background: orange;
}
</style>
</head>
<body>
<div id="parent">
父元素
<div id="child">
子元素
 <a href="http://www.baidu.com">点击我</a>
</div>
</div>
</body>
<script>
let parent = document.getElementById("parent");
let child = document.getElementById("child");
// 捕获事件
// document.body.addEventListener("click",function(){
// alert("捕获body");
// console.log("捕获body")
// },true)
// parent.addEventListener("click",function(){
// alert("捕获parent");
// console.log("捕获parent")
// },true)
// child.addEventListener("click",function(){
// alert("捕获child");
// console.log("捕获child")
// },true)
document.body.addEventListener("click", function () {
alert("冒泡body");
console.log("冒泡body")
})
parent.addEventListener("click", function () {
alert("冒泡parent");
console.log("冒泡parent")
})
parent.addEventListener("click", function () {
alert("额外的parent事件");
event.stopImmediatePropagation();
})
child.addEventListener("click", function () {
alert("冒泡child");
console.log("冒泡child")
})
// document.getElementsByTagName("a")[0].addEventListener("click",function(){
// return false;
// })
//方法一: event.stopPropagation();
//方法二: event.preventDefault();
//方法三: stopImmediatePropagation();
//方法四: return false;
// const log = console.log;
// document.body.onclick = function () {
// log(1);
// alert("冒泡body");
// console.log("冒泡body")
// return false;
// }
// parent.onclick = function () {
// log(2);
// alert("冒泡parent");
// console.log("冒泡parent")
// }
// child.onclick = function () {
// log(3);
// alert("冒泡child");
// console.log("冒泡child")
// }
// document.getElementsByTagName("a")[0].onclick = function () {
// return false;
// }
</script>
</html>



返回列表 返回列表
评论

    分享到