17-解决方案
13.4.2 解决方案
通过捕捉页间锚链接的 href="..." 属性,可以使用jQuery寻找目标ID,隐藏其兄弟节点,并将目标元素显示到前景中。这是一个简单的jQuery应用,但是能带来很好的效果。
1.选项卡——HTML代码
<!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-us" lang="en-us">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="imagetoolbar" content="false" />
<title>jQuery Cookbook - Ch.13 - Tabbing Through a Document</title>
<link rel="stylesheet" type="text/css" href="../_common/basic.css" />
<link rel="stylesheet" type="text/css" href="tabs.css" />
<script type="text/javascript">
/* <![CDATA[ */
document.write('<link rel="stylesheet" type="text/css" href="preload.css" />');
/* ]]> */
</script>
<script type="text/javascript" src="../_common/jquery.js"></script>
<script type="text/javascript" src="tabs.js"></script>
</head>
<body>
<div id="container">
<ul class="tabs">
<li>
<a href="#tab_content_primary_01" class="current">Tab Link 01</a>
</li>
<li>
<a href="#tab_content_primary_02">Tab Link 02</a>
</li>
<li>
<a href="#tab_content_primary_03">Tab Link 03</a>
</li>
<li>
<a href="#tab_content_primary_04">Tab Link 04</a>
</li>
<li>
<a href="#tab_content_primary_05">Tab Link 05</a>
</li>
</ul>
<div class="tab_content_wrap">
<div id="tab_content_primary_01" class="tab_content">
<p>
<strong>Content Area 01</strong>
</p>
<p>
Lorem ipsum...
</p>
</div>
<div id="tab_content_primary_02" class="tab_content">
<p>
<strong>Content Area 02</strong>
</p>
<p>
Duis ultricies ante...
</p>
</div>
<div id="tab_content_primary_03" class="tab_content">
<p>
<strong>Content Area 03</strong>
</p>
<p>
Morbi fringilla...
</p>
</div>
<div id="tab_content_primary_04" class="tab_content">
<p>
<strong>Content Area 04</strong>
</p>
<p>
Sed tempor...
</p>
</div>
<div id="tab_content_primary_05" class="tab_content">
<p>
<strong>Content Area 05</strong>
</p>
<p>
Nulla facilisi...
</p>
</div>
</div>
...
</div>
</body>
</html>
2.选项卡——jQuery代码
// 初始化
function init_tabs() {
// 元素存在吗?
if (!$('ul.tabs').length) {
// 如果不存在,退出
return;
}
//显示初始内容区域
$('div.tab_content_wrap').each(function() {
$(this).find('div.tab_content:first').show();
});
// 监听选项卡上的单击
$('ul.tabs a').click(function() {
// If not current tab.如果不是当前选项卡
if (!$(this).hasClass('current')) {
// 修改当前指示器
$(this).addClass('current').parent('li').siblings('li')
.find('a.current').removeClass('current');
//显示目标,隐藏其他选项卡
$($(this).attr('href')).show().siblings('div.tab_content').hide();
}
// Nofollow.
this.blur();
return false;
});
}
//启动
$(document).ready(function() {
init_tabs();
});