事件对象阻止默认行为
<!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>
* {
margin: 0;
padding: 0;
}
div {
float: left;
width: 200px;
height: 200px;
background-color: pink;
}
a {
text-decoration: none;
}
sub {
border-radius: 1px solid black;
}
</style>
</head>
<body>
<div>123</div>
<a href="http://www.baidu.com">百度</a>
<form action="http://www.baidu.com">
<input type="submit" value="提交" name="sub">
</form>
<script>
var div = document.querySelector('div');
var a = document.querySelector('a');
//返回点击或其他事件的type
function fn(e) {
console.log(e.type);
}
//绑定事件
div.addEventListener('click', fn);
div.addEventListener('mouseover', fn);
div.addEventListener('mouseout', fn);
//阻止默认跳转
//1.标准dom写法
a.addEventListener('click', function (e) {
e.preventDefault();
})
//2.传统阻止默认行为写法
a.onclick = function (e) {
return false;
//没有兼容性的问题,有一点需要注意:return后面的语句均不执行
}
</script>
</body>
</html>
点个关注再走呗~