效果:选中菜单和未选中菜单显示不同颜色。 思路:搭建横向菜单(CSS布局),给每个li绑定点击事件。$(this)代表当前点击的li,使用siblings()获取同级所有li,设置样式;再通过end()回到当前元素,修改自身样式。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm11.aspx.cs" Inherits="WebApplication1.WebForm11" %>
<!DOCTYPE html>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<style>
ul li {
float:left;
list-style-type:none;
padding-left:10px;
}
.current {
background-color:red;
}
.menu {
background-color:white;
}
</style>
<script type="text/javascript">
$(function () {
$('li').click(function () {
$(this).removeClass('menu').addClass("current").siblings().removeClass('current').addClass('menu');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul>
<li>首页</li>
<li>资讯</li>
<li>课程</li>
<li>下载</li>
<li>学生</li>
<li>搜索</li>
</ul>
</div>
</form>
</body>
</html>
Code language: HTML, XML (xml)
说明:点击li时,给当前元素添加选中样式current;其余同级兄弟元素移除选中样式,恢复默认menu样式。
Previous: 练习一下-完成一个评分控件
Next: 了解一下jQuery的链式编程