0

eu fiz um toggle button utilizando esse codigo:

// Hide all the elements in the DOM that have a class of "box"
$('.box').hide();

// Make sure all the elements with a class of "clickme" are visible and bound
// with a click event to toggle the "box" state
$('.clickme').each(function() {
    $(this).show(0).on('click', function(e) {
        // This is only needed if your using an anchor to target the "box" elements
        e.preventDefault();
        
        // Find the next "box" element in the DOM
        $(this).next('.box').slideToggle('fast');
    });
});
body {
    font: 12px/16px sans-serif;
    margin: 10px;
    padding: 0;
}

.clickme {
    background-color: #eee;
    border-radius: 4px;
    color: #666;
    display: block;
    margin-bottom: 5px;
    padding: 5px 10px;
    text-decoration: none;
}

.clickme:hover {
    text-decoration: underline;
}

.box {
    background-color: #ccc;
    border-radius: 4px;
    color: #333;
    margin: 5px 0;
    padding: 5px 10px;
    width: auto;
}
<a href="#" class="clickme">Click Me</a>
<div class="box">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

<a href="#" class="clickme">Click Me</a>
<div class="box">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

Mas estou com um problema bem chato em relação a quando se clica em mais de um toggle button eles acabam acumulando e fica bem feio img normal: inserir a descrição da imagem aqui img com os toggle buttons em show.

inserir a descrição da imagem aqui

Bom eu queria q só tivesse como abrir um por vez ou quando um abrir o outro fechar é possível fazer isso? Alguém poderia dar uma luz?

2 Respostas 2

2

voce pode utlizar o collapse bootstrap, e um script para altenar o fechamento das divs como por exemplo

<div id="accordion" role="tablist">
  <div class="card">
    <div class="card-header" role="tab" id="headingOne">
      <h5 class="mb-0">
        <a data-toggle="collapse" href="#collapseOne" role="button" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" role="tabpanel" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" role="tab" id="headingTwo">
      <h5 class="mb-0">
        <a class="collapsed" data-toggle="collapse" href="#collapseTwo" role="button" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" role="tabpanel" aria-labelledby="headingTwo" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" role="tab" id="headingThree">
      <h5 class="mb-0">
        <a class="collapsed" data-toggle="collapse" href="#collapseThree" role="button" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </a>
      </h5>
    </div>
    <div id="collapseThree" class="collapse" role="tabpanel" aria-labelledby="headingThree" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>
var active = true;
    $(document).on("click", ".accordion ","show.bs.collapse", function () {
        if (active)
            $(".accordion .in").collapse("hide");
    });
11
  • Mano eu não achei nenhum plugin pra baixar vc sabe dizer oq eu chamo na script p funcionar? Ou usa apenas esse codigo q vc mandou?
    – Felipe
    Commented 29/12/2017 às 1:48
  • Você tem que acrescentar o Jquery Commented 29/12/2017 às 1:51
  • jquery.com Commented 29/12/2017 às 1:52
  • Adicionar o bootstrap , baixe e acrescente no projeto junto com jquery Commented 29/12/2017 às 1:53
  • eu consigo acrescentar ele no meu codigo já feito?
    – Felipe
    Commented 29/12/2017 às 1:55
1

Para fechar todos os que já estão abertos, só iterar neles e dar outro toggle:

$('.clickme').each(function() {
    $(this).show(0).on('click', function(e) {
        e.preventDefault();

        $.each($('.box[style*="display: block"]'), function(i, v){
             $(v).slideToggle('fast');
        });

        $(this).next('.box').slideToggle('fast');
    });
});

Veja funcionando no jsfiddle.

3
  • obrigado mano!!
    – Felipe
    Commented 29/12/2017 às 1:02
  • Francisco eu estou com um problema eu adicionei, mas qnd clica para abrir o toggle ele fecha sozinho e não quando abre outro toggle pode ajudar pff?
    – Felipe
    Commented 29/12/2017 às 2:11
  • @Felipe Toggle ou collapse?
    – Francisco
    Commented 29/12/2017 às 10:59

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .