对通过document获取页面元素节点添加事件的考察
<!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>
</head>
<style>
#body {
width: 100vw;
height: 100vh;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
.black {
background-color: black;
}
.recover {
background-color: none;
}
</style>
<body id="body">
<button id="yellow">点击变黄</button>
<button id="green">点击变绿</button>
<button id="black">点击变黑</button>
<button id="recover">点击恢复</button>
<script>
let body = document.querySelector('#body');
yellow.addEventListener('click', () => {
let yellow = document.querySelector('#yellow'); // 获取按钮节点
body.setAttribute('class', 'yellow') // 给节点添加class属性
})
green.addEventListener('click', () => {
let green = document.querySelector('#green');// 获取按钮节点
body.setAttribute('class', 'green') // 给节点添加class属性
})
black.addEventListener('click', () => {
let black = document.querySelector('#black');// 获取按钮节点
body.setAttribute('class', 'black') // 给节点添加class属性
})
recover.addEventListener('click', () => {
let recover = document.querySelector('#recover');// 获取按钮节点
body.setAttribute('class', 'recover') // 给节点添加class属性
})
</script>
</body>
</html>