前端-JavaScript-练习-if-点击切换颜色
目录
前端 - JavaScript 练习 - if 点击切换颜色
点击切换颜色
一、三色切换 - 点击切换颜色
<!--
* @Date: 2021-09-02 10:49:29
* @LastEditTime: 2021-09-02 15:02:15
* @总结:
-->
<!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>
<style>
.light {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border-radius: 40%;
background: yellow;
}
</style>
<body>
<div class="light" id="light"></div>
<script>
/*
需求:
当是红灯时,点击后变为黄灯;
当是黄灯时,点击后变为绿灯;
当是绿灯时,点击后变为红灯;
*/
// 获取文档中 id 为 light 的标签
const light = document.getElementById('light');
// 1代表: red 2代表: yellow 3代表: green
let color = 2;
light.onclick = function () {
if (color == 1) {
light.style.background = "yellow";
color = 2;
} else if (color == 2) {
light.style.background = "green";
color = 3;
} else if (color == 3) {
light.style.background = "orange";
color = 1;
}
}
</script>
</body>
</html>
以下代码,可以使绝对定位后脱离文档流的元素进行居中
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
二、双色切换 - 点击切换颜色(适用于 二选一的情景)
<!--
* @Date: 2021-09-02 11:21:00
* @LastEditTime: 2021-09-02 15:06:33
* @总结:
-->
<!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>
<style>
.btn {
outline: none;
border: none;
height: 64px;
font-weight: 120px;
}
.box {
width: 300px;
height: 300px;
background: yellow;
}
</style>
</head>
<body>
<button type="button" id="btn" class="btn">点赞</button>
<div id="box" class="box"></div>
<script>
const btn = document.getElementById("btn");
const box = document.getElementById("box");
let state = true;
btn.onclick = function () {
if (state) {
box.style.background = "red";
} else {
box.style.background = "yellow";
}
state = !state;
}
</script>
</body>
</html>
后续内容持续更新中…