dom綁定事件有兩種方法:
- onclick
onclick綁定事件骇径,分為兩種方法玷氏,一種是行內(nèi)綁定姥卢,一種是動態(tài)綁定
行內(nèi)綁定:
行內(nèi)綁定,事件中的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>
動態(tài)綁定:
<!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>
- 添加事件監(jiān)聽
<!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() {
// 事件監(jiān)聽的方法扶平,添加的事件帆离,可以重復(fù)多次添加同一事件,并同時生效
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>