一个简单的js实现Tab切换效果

-- Submitted by Admin on Fri, 04/23/2010 - 15:17

写了一个Tab切换的效果。自以为比用jquery ui的tab要更简单。

HTML结构:

<dl class="tab">
  <dt><a class="tab" href="#tab-1">故事</a> <a class="tab" href="#tab-2">散文</a> <a class="tab" href="#tab-3">漫画</a></dt>
  <dd class="tab" id="tab-1">故事内容</dd>
  <dd class="tab" id="tab-2">散文内容</dd>
  <dd class="tab" id="tab-3">漫画内容</dd>
</dl>

CSS样式:

<style type="text/css">
  dd.tab { display:none;}
  #tab-1 { display:block;}
  dl.tab { border:1px solid #000;}
  .tab dt { margin:10px;}
  .tab dd { border:1px solid green; margin:10px; padding:10px;}
  a.tab { background-color:#eee; color:f63; padding:5px 10px; text-decoration:none;}
  a.tab:hover { background-color:#f63; color:#fff; text-decoration:none;}
  </style>

JS代码:

  $(document).ready(function(){

$('a.tab').mouseover(function(){
var tab = $(this).attr('href');
$('dd.tab').hide();
$(tab).css('display','block'); //.show()的结果是display:inline;会使某些样式失效,如padding margin。
});

$('a.tab').click(function(){
var tab = $(this).attr('href');
$('dd.tab').css('display','none');
$(tab).css('display','block');
return false;
});

  });

代码说明:

这些代码并不深奥,了解的人就应该能看得懂原理。重点是保证 a.tab 的 id 和相应dd.tab  的 id 相对应。

DEMO见附件

PreviewAttachmentSize
tab_demo.rar32.9 KB

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <em> <strong> <code> <cite> <ul> <ol> <li> <dl> <dt> <dd> <img> <ebmed>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.