dom绑定事件有两种方法:
- onclick
onclick绑定事件,分为两种方法,一种是行内绑定,一种是动态绑定
行内绑定:
行内绑定,事件中的this指向window
<!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>
<script>
function display() {
// this.style.background = 'yellow';
console.log(this);
}
</script>
<style>
#test, #box {
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<div id="test" onclick="display()"></div>
</body>
</html>
动态绑定:
<!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>
<script>
window.onload = function() {
document.getElementById('box').onclick = function() {
this.style.width = '500px';
}
}
</script>
<style>
#test, #box {
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>
- 添加事件监听
<!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>
<script>
window.onload = function() {
// 事件监听的方法,添加的事件,可以重复多次添加同一事件,并同时生效
document.getElementById('box').addEventListener('click', function() {
this.style.background = 'yellow';
});
document.getElementById('box').addEventListener('click', function () {
this.style.width = '500px';
});
}
</script>
<style>
#test, #box {
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>
网友评论