Javascript如何阻止事件冒泡和事件本身发生
4640
Javascript如何阻止事件冒泡和事件本身发生
1、阻止事件冒泡发生
<!DOCTYPE html>
<html>
<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>
.boxA {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: blue;
text-align: center;
}
.boxB {
width: 200px;
height: 200px;
margin: 50px;
background-color: green;
line-height: 200px;
color: #fff;
}
</style>
</head>
<body>
<div>
<div>boxB</div>
</div>
<script>
var boxA = document.querySelector('.boxA');
var boxB = document.querySelector('.boxB');
boxA.onclick = function (e) {
console.log('我被点击了boxA');
};
boxB.onclick = function (e) {
e.cancelBubble=true; //不冒泡
console.log('我被点击了boxB');
};
</script>
</body>
</html>2、阻止事件本身发生
<!DOCTYPE html>
<html>
<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>
</head>
<form action="http://www.php.cn" method="POST">
<button type="submit">按钮1</button>
</form>
<body>
<script>
const btn=document.querySelector("button");
console.log(btn);
btn.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>本文网址:https://www.zztuku.com/detail-8779.html
站长图库 - Javascript如何阻止事件冒泡和事件本身发生
申明:如有侵犯,请 联系我们 删除。








您还没有登录,请 登录 后发表评论!
提示:请勿发布广告垃圾评论,否则封号处理!!