通过html写一个按钮
<button id="btn">点击</button>
写一个块状颜色
<!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>
<style>
* {
padding: 0;
margin: 0;
}
.box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409eff;
text-align: center;
color: #fff;
box-sizing: border-box;
margin-right: 20px;
}
</style>
</head>
<body>
<button id="btn">点击</button>
<div class="box"></div>
</body>
</html>
接下来写一个 按钮操作 ,点击的js逻辑 点击出现,再次点击消失的过度效果
<script>
let btn = document.getElementById("btn");
let box = document.getElementsByClassName("box")[0];
let flag = true;
btn.onclick = function () {
if (flag) {
box.style.height = "0px";
} else {
box.style.height = "100px";
}
flag = !flag;
};
</script>
补全代码
<!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>
<style>
* {
padding: 0;
margin: 0;
}
.box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409eff;
text-align: center;
color: #fff;
box-sizing: border-box;
margin-right: 20px;
transition: height 2s;
}
</style>
</head>
<body>
<button id="btn">点击</button>
<div class="box"></div>
</body>
<script>
let btn = document.getElementById("btn");
let box = document.getElementsByClassName("box")[0];
let flag = true;
btn.onclick = function () {
if (flag) {
box.style.height = "0px";
} else {
box.style.height = "100px";
}
flag = !flag;
};
</script>
</html>
效果图
如果我们实现一个缓慢展开 快速折叠的效果如何实现?
代码如下
<!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>
<style>
* {
padding: 0;
margin: 0;
}
.box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409eff;
text-align: center;
color: #fff;
box-sizing: border-box;
margin-right: 20px;
/* transition: height 2s; */
}
</style>
</head>
<body>
<button id="btn">点击</button>
<div class="box"></div>
</body>
<script>
let btn = document.getElementById("btn");
let box = document.getElementsByClassName("box")[0];
let flag = true;
btn.onclick = function () {
if (flag) {
box.style.transition = "height .5s";
box.style.height = "0px";
} else {
box.style.transition = "height 2s";
box.style.height = "100px";
}
flag = !flag;
};
</script>
</html>
效果可自行查看