本節示範如何用 jQuery 讓選項卡自動定時切換,適合用於新聞、焦點等需要輪播的區塊。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>自動切換 tabs 選項卡</title>
<!-- 注意引入檔案的順序,沒有效果很可能就是引入順序不對! -->
<script type="text/javascript" src="<%=path %>/js/jquery-1.2.6.js"></script>
<script src="<%=path%>/js/ui.core.js" type="text/javascript"></script>
<link href="<%=path%>/css/ui.tabs.css" rel="stylesheet" type="text/css" />
<script src="<%=path%>/js/ui.tabs.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#rotate > ul').tabs({ fx: { opacity: 'toggle' },selected:0}).tabs('rotate', 500000);
});
</script>
</head>
<body>
<div id="rotate">
<ul>
<li><a href="#div1"><span>新聞</span></a></li>
<li><a href="#div2"><span>論壇</span></a></li>
<li><a href="#div3"><span>博客</span></a></li>
</ul>
<div id="div1"><h4>DIV1</h4>此處放置測試內容。</div>
<div id="div2"><h4>DIV2</h4>此處放置測試內容。</div>
<div id="div3"><h4>DIV3</h4>此處放置測試內容。</div>
</div>
</body>
</html>
關鍵在於 .tabs('rotate', 500000) 這個呼叫,它會讓選項卡每隔一段時間自動切換。另外要特別注意各 js 檔案的引入順序,順序不對往往是效果出不來的主因。