DIV CSS 佈局教程網

用 jQuery 實現 panel 的伸展與合攏效果
編輯:JavaScript綜合知識     

可折疊的面板能讓頁面更清爽,也方便使用者按需展開或收起內容。本文將介紹如何用 jQuery 實現 panel 的伸展與合攏效果,可實現 div 層的平滑收縮與展開,涉及 next、slideUp、slideDown 等方法的運用,簡單又實用。

完整代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>jQuery伸展與合攏的Panel演示</title>
<style type="text/css">
*{margin:0;padding:0;}
body { font-size: 13px; line-height: 130%; padding: 60px }
#panel { width: 300px; border: 1px solid #0050D0 }
.head { padding: 5px; background: #96E555; cursor: pointer }
.content { padding: 10px; text-indent: 2em; border-top: 1px solid #0050D0;display:block; }
</style>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
  $("#panel h5.head").toggle(function(){
    $(this).next("div.content").slideUp();
  },function(){
    $(this).next("div.content").slideDown();
  })
})
</script>
</head>
<body>
<div id="panel">
<h5 class="head">點擊這裡</h5>
<div class="content">
展開和收起的內容!展開和收起的內容!展開和收起的內容!
展開和收起的內容!展開和收起的內容!展開和收起的內容!
展開和收起的內容!展開和收起的內容!
</div>
</div>
</body>
</html>

核心思路非常簡潔:透過 toggle 方法切換兩種行為,第一次點擊標題時用 slideUp 收起內容,再次點擊則用 slideDown 展開;而 next("div.content") 則用來定位標題後緊鄰的內容層。借助 jQuery 內建的滑動動畫,便能實現流暢自然的折疊效果。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved