<!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>事件案例 - 开关灯</title>
</head>
<body>
<button>关灯</button>
</body>
<script>
// 需求:点击关灯 背景被黑,文字变成关灯. 反之反过来
// 1.获取事件源
const btn = document.querySelector("button");
console.log(btn);
// 2.确定事件类型:点击事件
btn.onclick = function () {
// 3. 事件处理
// 3.1 获取条件: 按钮.innerText,然后判定
if (this.innerText == "开灯") {
// 3.2 开灯: body背景变白, 文字变成关灯
this.innerText = "关灯";
document.body.style.backgroundColor = "#fff";
} else if (this.innerText == "关灯") {
// 3.3 关灯: body背景变黑, 文字变成开灯
this.innerText = "开灯";
// body在页面中只有一个Ldocument对象专门提供了一个属性:body,表示当前body元素
console.log(document.body);
document.body.style.backgroundColor = "#000";
}
};
// 总结
// 1. 获取元素的复习: document.querySelector()
// 2. 事件的复习: 事件源.事件类型 = function(){}
// 3. 样式操作: 元素.style.样式名 = 值 元素.innerText获取和修改
// 新知识: 获取body的方式: document.body
</script>
</html>
JavaScript - WebAPI - 案例 - 开关灯
最新推荐文章于 2022-04-16 12:47:22 发布