<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
<style>
#menu{width: 300px;}
.has-children{background: #555;color: #fff; cursor: pointer;}
.highlight{color: #fff;background: green;}
div{padding:0px;margin:0px;}
div a{background:#888;display: none;float:left; width: 300px;}
</style>
<script src="scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
//等待dom元素加载完毕.
$(document).ready(function(){
$(".has-children").click(function(){
$(this).addClass("highlight")//为当前元素增加lighlight类
.children("a").show().end()//将子节点的<a>元素显示出来并重新定位到上次操作的元素
.siblings().removeClass("highlight")//获取元素兄弟的元素,并去掉它们的highlight类
.children("a").hide();//将兄弟元素下的a元素隐藏
});
});
</script>
</head>
<body>
<div id="menu">
<div class="has-children">
<span>第一章-认识Jquery</span>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
</div>
<div class="has-children">
<span>第二章-Jquery选择器</span>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
</div>
<div class="has-children">
<span>第三章-Jquery中的dom操作</span>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
<a>1.1-JavaScript和JavaScript库</a>
<a>1.2-加入jquery</a>
</div>
</div>
</body>
</html>
代码运行效果如图:

本文详细介绍了一种使用jQuery库实现网页菜单项折叠与展开的交互效果。通过为具有子菜单项的菜单添加特定的CSS类和jQuery事件监听器,实现了点击父级菜单时子菜单的显示与隐藏。此外,还提供了代码示例和运行效果,便于读者理解和实践。

被折叠的 条评论
为什么被折叠?



