想想到现在已经有一段时间没有更新了,前一段时间忙着面试,过一段时间我会把我的面试用来复习的面试题整理整理发出来
下面,我们来用css+js实现手风琴下拉菜单效果,话不多说,直接上代码
<!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>
</style>
</head>
<body>
<div class="accordion">
<ul>
<li class="masterwork">
<span>四大名著</span>
<ul class="xiala">
<li>
<span>《西游记》</span>
</li>
<li>
<span>《红楼梦》</span>
</li>
<li>
<span>《水浒传》</span>
</li>
<li>
<span>《三国演义》</span>
</li>
</ul>
</li>
<li class="masterwork">
<span>有关爱情名著</span>
<ul class="xiala">
<li>
<span>《霍乱时期的爱情》</span>
</li>
<li>
<span>《飘》</span>
</li>
<li>
<span>《简·爱》</span>
</li>
<li>
<span>《呼啸山庄》</span>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
此时效果图如下
加上css代码
<style>
/* 去除所有标签的外边距内边距 */
* {
margin: 0;
padding: 0;
}
.accordion {
padding: 10px;
}
ul {
background-color: aqua;
width: 156px;
}
li {
list-style: none;
background-color: aqua;
}
span {
display: inline-block;
width: 150px;
padding: 3px;
}
.masterwork > ul {
display: none;
}
</style>
此时的效果如图
添加点击事件
<script>
let click = document.querySelectorAll(".masterwork>span")
for (const i in click) {
click[i].onclick = function (e) {
console.log(e.target) //检查是否获取到点击事件
let xiala = click[i].parentNode.children[1].classList.value//获取对应的class吃否存在
//判断class是否存在
if (!xiala) {
// 显示
click[i].parentNode.children[1].classList.add("xiala")
} else {
// 隐藏
click[i].parentNode.children[1].classList.remove("xiala")
}
}
}
</script>
效果如下视频
css+js手风琴
完整代码如下:
<!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>
/* 去除所有标签的外边距内边距 */
* {
margin: 0;
padding: 0;
}
.accordion {
padding: 10px;
}
ul {
background-color: aqua;
width: 156px;
}
li {
list-style: none;
background-color: aqua;
}
span {
display: inline-block;
width: 150px;
padding: 3px;
}
.masterwork > .xiala {
display: none;
}
.aaa {
display: block !important;
}
</style>
</head>
<body>
<div class="accordion">
<ul>
<li class="masterwork">
<span>四大名著</span>
<ul class="xiala">
<li>
<span>《西游记》</span>
</li>
<li>
<span>《红楼梦》</span>
</li>
<li>
<span>《水浒传》</span>
</li>
<li>
<span>《三国演义》</span>
</li>
</ul>
</li>
<li class="masterwork">
<span>有关爱情名著</span>
<ul class="xiala">
<li>
<span>《霍乱时期的爱情》</span>
</li>
<li>
<span>《飘》</span>
</li>
<li>
<span>《简·爱》</span>
</li>
<li>
<span>《呼啸山庄》</span>
</li>
</ul>
</li>
</ul>
</div>
</body>
<script>
let click = document.querySelectorAll(".masterwork>span")
for (const i in click) {
click[i].onclick = function (e) {
console.log(e.target) //检查是否获取到点击事件
let xiala = click[i].parentNode.children[1].classList.value
console.log()
if (!xiala) {
// 显示
click[i].parentNode.children[1].classList.add("xiala")
} else {
// 隐藏
click[i].parentNode.children[1].classList.remove("xiala")
}
}
}
</script>
</html>
感谢您能看完我的作品,感谢您的支持