1、事件绑定(onclick
、addEventListener
)
区别 | onclick 与addEventListener |
---|
onclick | 在同一元素的同一事件类型添加多个事件,会被覆盖。不可以设置元素在捕获阶段触发的事件 |
addEventListener | 在同一元素的同一事件类型添加多个事件,不会被覆盖。可以设置元素在捕获阶段(从外到内)触发的事件 |
<script>
var btn = document.querySelector('button');
btn.onclick = function () {
console.log('Hello world!');
}
btn.addEventListener("click", function () {
console.log('Hello world!');
})
</script>
2、事件流(addEventListener
)
- 当事件被触发时,事件有两个流向,一个是从内到外(事件冒泡),一个是从外到内(事件捕获)
- 默认情况下,事件会在冒泡阶段运行
addEventListener(evenType.fun,boolean)
//默认false:冒泡阶段触发;true:捕获阶段触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.big {
width: 300px;
height: 300px;
background-color: black;
}
.medium {
width: 200px;
height: 200px;
background-color: bisque;
}
.small {
width: 100px;
height: 100px;
background-color: aquamarine;
}
</style>
</head>
<body>
<button>button</button>
<div class="big">
<div class="medium">
<div class="small"></div>
</div>
</div>
<script>
var btn = document.querySelector('button');
btn.onclick = function () {
console.log('Hello world!');
}
btn.addEventListener("click", function () {
console.log('Hello world!');
})
var big = document.querySelector('.big');
var medium = document.querySelector('.medium');
var small = document.querySelector('.small');
big.addEventListener('click', function () {
console.log('big');
});
medium.addEventListener('click', function () {
console.log('medium');
});
small.addEventListener('click', function () {
console.log('small');
});
</script>
</body>
</html>
3、阻止事件冒泡(stopPropagation
)
small.addEventListener('click', function (e) {
console.log('small');
e.stopPropagation();
});
3、取消元素默认行为(preventDefault
)
<body>
<a href='https://www.iconfont.cn'>阿里巴巴矢量库</a>
<script>
var a = document.querySelector('a');
a.onclick = function (e) {
console.log('Hello world!');
e.preventDefault();
return false;
}
</script>
</body>
</html>