【问题标题】:Make current div change relevant menu tab to active使当前 div 将相关菜单选项卡更改为活动状态
【发布时间】:2016-09-30 18:06:56
【问题描述】:

在我的移动项目中,我可以按下一个菜单选项卡 (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
  }
});

有关我正在尝试构建的内容的更多详细信息,包括。库、图像(以及我之前的问题,由“Pieter”解决):

Link to a section on horizontal web page

【问题讨论】:

  • 你在所有条件下都写了相同的东西...?

标签: javascript jquery html css


【解决方案1】:

正如我上面评论的那样,您在所有情况下都在做同样的事情。您需要做的就是通过您从轮播中获得的索引激活导航项。试试这个:

$('#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
});

【讨论】:

  • 你可能想重置其他css
  • 虽然我是单行的,但是调用很多方法会以某种方式降低性能。我会选择$('.nav-pills&gt;li').removeClass('...').. 作为实时场景中的 3-4,项目的长度可能会超过 OP 中的共享..
  • @Rayon 对 3-4 个项目进行操作几乎不会影响性能。但我同意这一点。 :)
  • @Ashish ...您先生是个天才!我自己永远也猜不到!非常感谢!
  • 你是最受欢迎的伙伴...我很高兴能帮上忙。干杯!!
【解决方案2】:

标签上已经有类名“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。)

【讨论】:

    猜你喜欢
    • 2014-05-23
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多