Adding .active class to div when a button is clicked?

时间:2015-09-01 21:59:35

标签: jquery html css twitter-bootstrap

I'm using bootstrap's tab system for a "set your account up" page and at the top of the page I have the different steps which are displayed at the top of the page above the tab-panes. I am trying to make it so when someone clicks an option in step one it will load the step two tab and add the active class to the appropriate steps div. I got this working, but can't figure out how to highlight the step you're currently on. So if you're on step one which is to finish your basic profile, then click save and continue at the bottom, it loads the next tab/step and adds the active class to the appropriate div for that step.

So, essentially I want to have the steps hand off the "active" class similar to how the bootstrap default tabs function where the one you're on is the one highlighted, except these "steps" divs aren't actually part of the tab system, just need to be affected by it.

Thank you!

tabs and steps

3 个答案:

答案 0 :(得分:2)

  

我试图这样做,当有人点击第一步中的选项时,它会加载第二步选项卡,并将活动类添加到相应的步骤div。

因为您没有提供任何标记。我假设你不知道从哪里开始。如果您浏览Bootstrap文档,所有这些都可以放在一起。

首先,使用data-toggle="tab"属性设置标签标记。

<div class="text-center"> 
 <a class="btn btn-primary" href="#step1" data-toggle="tab">Step 1</a>
 <a class="btn btn-default" href="#step2" data-toggle="tab">Step 2</a>
 <a class="btn btn-default" href="#step3" data-toggle="tab">Step 3</a>
</div>

接下来,使用包含按钮的单个窗格设置标签内容。

<div class="tab-content">
  <div id="step1" class="tab-pane active">
     <div>
        <h1>Step 1</h1>
     </div>
     <div class="text-right"> 
         <a class="btn btn-default next" href="#">Next</a>
     </div>
  </div>
  ...
</div>

使用Bootstrap提供的示例shown.bs.tab在显示标签后,此标签会在标签显示中触发。

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  e.target // newly activated tab
  e.relatedTarget // previous active tab
})
  

因此,如果您正在完成基本配置文件的第一步,则单击保存并继续在底部,它会加载下一个选项卡/步骤并将活动类添加到该步骤的相应div。

创建点击事件以收听按钮点击并显示下一个窗格。

$('.next').click(function () {
    var nextId = $(this).parents('.tab-pane').next().attr("id");
    $('[href=#' + nextId + ']').tab('show');
});

这里有一个小提琴,所有这些都放在一起供你查看。 http://jsfiddle.net/kmx4zx6n/

答案 1 :(得分:0)

In css use something like this:

.step div { background-color: red; } .step.active div { background-color: blue; }

It's what you want?

答案 2 :(得分:0)

使用Jquery addClassremoveClass

<强> JQUERY

$('.main-class a').on('click',function(){
  $('a').removeClass('active');
  $(this).addClass('active');
});

<强> HTML

<div class="main-class text-center"> 
 <a class="btn btn-default active" href="#step1" data-toggle="tab">Step 1</a>
 <a class="btn btn-default" href="#step2" data-toggle="tab">Step 2</a>
 <a class="btn btn-default" href="#step3" data-toggle="tab">Step 3</a>
</div>

<强> CSS

.active{
    background-color:green !important;
  }

DEMO