使当前div更改相关菜单选项卡激活

时间:2016-06-01 11:36:26

标签: javascript jquery html css

在我的移动项目中,我可以按菜单选项卡(Tab2)并且选项卡变为活动状态(活动类的背景颜色),并且屏幕上将显示下面相应的div(Div2)。 如果我按下另一个选项卡,该选项卡将与corr一起激活。 div等......总之,工作完美!

但是现在我遇到了相反的问题,我想在我的屏幕上按下(在我的情况下,滑动)一个div并让上面的相应标签处于活动状态(带颜色)。例如在屏幕上的Div1中滑动,Tab1应该处于活动状态并具有特定的背景颜色。在Div2中滑动,然后Tab2应该是活动的,而不是等等,但不能使它工作。

以下是我的li标签:

<ul class="nav nav-pills mobileNavbar">
  <li onclick="swipeFunction(0)" class="col-xs-4 tab1" data-index="0"><a href="#">STREAM</a></li>
  <li onclick="swipeFunction(1)" class="col-xs-4 tab2" data-index="1"><a href="#">CHAT</a></li>
  <li onclick="swipeFunction(2)" class="col-xs-4 tab3" data-index="2"><a href="#">IDE</a></li>
</ul>

我的jQuery:

$('#carousel-example-generic').on('slid.bs.carousel', function() {

  var savedIndex = $(this).find('.active').index();

  if (savedIndex === 0){
    // I want Tab1 to be active here
  } else if (savedIndex == 1){
    // I want Tab2 to be active here
  } else if (savedIndex == 2){
    // I want Tab3 to be active here
  }
});

有关我正在尝试构建的内容的详细信息,包括。图书馆,图像(以及我之前的问题,由#34; Pieter&#34;解决):

Link to a section on horizontal web page

2 个答案:

答案 0 :(得分:2)

正如我上面评论的那样,你在所有条件下做同样的事情。您需要做的就是,通过旋转木马获得的索引激活导航项。试试这个:

$('#carousel-example-generic').on('slid.bs.carousel', function () {

    var savedIndex = $(this).find('.active').index();

    $('.nav-pills>li:eq(' + savedIndex + ')>a').css('background', 'yellow');
});

修改

我建议使用CSS类而不是内联css。试试这个:

$('#carousel-example-generic').on('slid.bs.carousel', function () {

    var savedIndex = $(this).find('.active').index();

    $('.nav-pills>li:eq(' + savedIndex + ')>a')
        .addClass("active") // add active class to the current one
        .parent().siblings() // select sibling navigation items
        .removeClass("active"); // remove active class from the other navigations
});

答案 1 :(得分:0)

您方便地在标签页上已经有类名“tab1”,“tab2”,“tab3”,可以根据savedIndex轻松匹配:

$('#carousel-example-generic').on('slid.bs.carousel', function() {
  $('.nav li').removeClass('active'); // clear the old one
  var savedIndex = $(this).find('.active').index();
  $('.tab'+ (savedIndex+1)).addClass('active'); // add the new one
});

(我相信index()会返回一个整数,但如果不是,则在添加1之前可能需要parseInt。)