body部分:主菜单栏和子菜单栏,为了方便循环遍历,将主菜单栏和子菜单栏放置在同一个父类div中
<body>
<div class="main_d">
<div class="menu_up">
<a href="#">菜单栏</a>
</div>
<div class="seg">
</div>
<div class="menu">
<div class="menu_d">
<div class="title_d">
主标题
</div>
<div class="content_d">
<a href="#">子标题</a>
<a href="#">子标题</a>
</div>
</div>
<div class="menu_d">
<div class="title_d">
主标题
</div>
<div class="content_d">
<a href="#">子标题</a>
<a href="#">子标题</a>
</div>
</div>
<div class="menu_d">
<div class="title_d">
主标题
</div>
<div class="content_d">
<a href="#">子标题</a>
<a href="#">子标题</a>
</div>
</div>
<div class="menu_d">
<div class="title_d">
主标题
</div>
<div class="content_d">
<a href="#">子标题</a>
<a href="#">子标题</a>
</div>
</div>
<div class="menu_d">
<div class="title_d">
主标题
</div>
<div class="content_d">
<a href="#">子标题</a>
<a href="#">子标题</a>
</div>
</div>
</div>
</div>
</body>
css部分
<style>
.{
padding: 0;
margin: 0;
}
.main_d{
width: 20%;
height: 600px;
background-color: gainsboro;
}
.menu_up{
width: 100%;
height: 50px;
float: lift;
}
.menu_up>a{
display: block;
width: 100%;
height: 50px;
/*垂直居中*/
line-height: 50px;
/*水平居中*/
text-align: center;
/*去除a标签下划线*/
text-decoration: none;
/*颜色*/
color: white;
}
.seg{
widows: 100%;
height: 1px;
background-color: black;
}
.title_d{
width: 100%;
height: 50px;
color: white;
line-height: 50px;
text-align:center;
/*鼠标划过显示手型*/
cursor: pointer;
}
.content_d{
width: 100%;
height: 100%;
}
.content_d>a{
display: block;
width: 100%;
height: 30px;
color: white;
line-height: 30px;
text-align: center;
background-color: black;
text-decoration: none;
font-size: 14px;
}
.content>a::before{ /*之前添加,此处为子菜单a前面的蓝色线条*/
content: ""; /*内容*/
width: 6px;
height: 100%;
background: #3498db;
left:0;
top:0;
transition: 0.3s; /*过渡时间*/
opacity: 0; /*透明度*/
}
.content>a:hover::before{ /*悬停时*/
opacity: 1;
}
.content_d>a:hover{
display: block;
width: 100%;
height: 30px;
color: white;
line-height: 30px;
text-align: center;
background-color: red;
text-decoration: none;
font-size: 20px;
}
</style>
jquery部分:
<script>
$(function(){
/*当页面显示结束再执行此函数*/
$(".content_d").each(function(){
/*将content子标题隐藏*/
$(this).hide();
})
/*遍历主标题*/
$(".title_d").each(function(){
/*为主标题添加点击事件*/
$(this).click(function(){
/*由主标题的父节点找到子标题*/
var div_content=$(this).parents(".menu_d").children(".content_d");
/*判断子标题是否显示*/
if(div_content.css("display")!="none"){
/*如果显示将其隐藏*/
div_content.slideUp(500);
}else{
/*由子标题找到其父节点*/
var div_menu=div_content.parents(".menu_d");
/*由siblings()方法找到其他父节点兄弟节点*/
var other_menu=div_menu.siblings();
/*遍历所有的兄弟节点*/
other_menu.each(function(){
/*找到其他兄弟节点的子节点content,并隐藏*/
$(this).children(".content_d").slideUp(500);
})
/*如果不显示将其显示*/
div_content.slideDown(500);
}
})
})
})
</script>