如何使jQuery tabs-btn默认关闭

时间:2015-12-28 23:29:14

标签: jquery html tabs

我正在使用代码来隐藏/显示来自链接的div:



$(function() {
  $('.tabs').myTabs({
    // container of navigation inside '.tabs'
    nav: '.tab-btns',
    // container of contents inside '.tabs'
    tabs: '.tab-contents'
  });
});

$.fn.myTabs = function(settings) {
  return this.each(function() {

    /*
save cached version of the first elements inside the containers. by calling the first elements of each container you are not limitng the plugin user to any specific class or elememt.
*/
    var btns = $(settings.nav, this).children(),
      tabs = $(settings.tabs, this).children();


    /* we relying on the order of the elements as the conection between the buttons and the tabs  
notice that .each() get the index of the btn..
we are useinf it to find the current tab.
*/

    btns.each(function(index) {
      var btn = $(this),
        tab = tabs.eq(index);


      btn.click(function(e) {
        /* prevent unnesscry work by checking if the button clicked is already active  */
        if (btn.is('.active')) return false;

        /* notice that first filter to find the last 'active' button before we remove the 'active' class  otherwise it remove the class for every button. unnesscry work prevented again */
        btns.filter('.active').removeClass('active');

        /* hide previus tab.. */
        tabs.filter(':visible').hide();

        btn.addClass('active');
        tab.show();


        return false;
      });
    });

    // emulate click on the first tab button;
    btns.first().click();
  });
};

.tab-btns .active {
  font-weight: bold;
}

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="tabs">
  <nav class="tab-btns">
    <a href="#tab1">tab btn 1</a>
    <a href="#tab2">tab btn 2</a>
    <a href="#tab3">tab btn 3</a>
    <a href="#tab4">tab btn 4</a>
  </nav>
  <div class="tab-contents">
    <div id="tab1">tab content 1</div>
    <div id="tab2">tab content 2</div>
    <div id="tab3">tab content 3</div>
    <div id="tab4">tab content 4</div>
  </div>
</div>
&#13;
&#13;
&#13;

是否可以进行导航&#39; divs(tabs tbn1等)默认隐藏?

1 个答案:

答案 0 :(得分:0)

这样做:

 $('.tab-contents').find('div:not(":first")').hide(); // if you want to hide all divs except for 1st one.
 $('.tab-contents div').hide(); // if you want to hide all divs 
 $('.tab-btns a').on("click",function()
 {
    $('.tab-contents div').hide();
    $($(this).attr('href')).show();
 });

示例:https://jsfiddle.net/DinoMyte/kqd7wfLc/5/

当您已经拥有内置API来处理标签时,这是一种非常蹩脚的方法。 jquery Tabs