思路:
- 利用input中的checkbox来区分是否收缩
- 通过js设置初始高度(不设置无法实现过渡效果)
- 通过过渡实现缓慢动画
全部代码
<!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>
<style>
* {
padding: 0;
margin: 0;
}
/* 大盒子 */
.content {
width: 80%;
margin: 100px auto;
border: 1px solid pink;
}
/* 题目 */
.title {
padding: .2em;
display: flex;
justify-content: space-between;
position: relative;
color: #fff;
background: pink;
border-bottom: 1px solid #fff;
}
/* input */
.input {
display: none;
}
/* 模拟选中后效果 */
#checkbox1:checked~#content1,
#checkbox2:checked~#content2,
#checkbox3:checked~#content3 {
height: 0 !important;
}
#checkbox1:checked~.title .arr,
#checkbox2:checked~.title .arr,
#checkbox3:checked~.title .arr {
transform: rotate(0);
}
/* 内容 */
.main {
transition: all .3s;
overflow: hidden;
}
.arr {
display: inline-block;
transform: rotate(90deg);
transition: all .3s;
}
</style>
</head>
<body>
<div class="content">
<div>
<input type="checkbox" id="checkbox1" class="input" />
<label for="checkbox1" class="title">
<span>列表1</span>
<span class="arr">></span>
</label>
<div class="main" id="content1">
<p>1</p>
</div>
</div>
<div>
<input type="checkbox" id="checkbox2" class="input" />
<label for="checkbox2" class="title">
<span>列表2</span>
<span class="arr">></span>
</label>
<div class="main" id="content2">
<p>1</p>
<p>1</p>
</div>
</div>
<div>
<input type="checkbox" id="checkbox3" class="input" />
<label for="checkbox3" class="title">
<span>列表3</span>
<span class="arr">></span>
</label>
<div class="main" id="content3">
<p>1</p>
<p>1</p>
<p>1</p>
</div>
</div>
</div>
<script>
var dom1 = document.getElementById("content1")
var dom2 = document.getElementById("content2")
var dom3 = document.getElementById("content3")
dom1.style.height = dom1.offsetHeight + "px"
dom2.style.height = dom2.offsetHeight + "px"
dom3.style.height = dom3.offsetHeight + "px"
</script>
</body>
</html>