¿Cómo cerrar automáticamente todos los elementos plegables dentro del acordeón al cerrar el acordeón?

El complemento Collapse proporciona una forma rápida de revelar y ocultar contenido. Cambia la perceptibilidad del contenido sobre el programa con un par de clases y complementos de JavaScript de Bootstrap 4.

Voltear (alternar) el contenido requiere conectarse con el atributo href , o un botón con la propiedad de destino de datos . En ambos casos, se requiere data-toggle=”collapse” .

Sintaxis: 

Enlace con el atributo href .

<a data-toggle="collapse" href="#collapseExample" ...>
    <!--Write your link name -->
</a>

O

Botón con la propiedad de destino de datos .

<button class="btn btn-primary" type="button" 
    data-toggle="collapse" 
    data-target="#collapseExample" ...>
    <!--Write your button name-->
</button>

 

Para mostrar la tarjeta:

<div class="collapse" id="collapseExample">
    <div class="card card-body">
        <h5 class="card-title"><!--Write title name--></h5>
        <!--Write content here -->
    </div>
</div>

Ejemplo:

HTML

<!doctype html>
<html lang="en">
  
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,
            initial-scale=1, shrink-to-fit=no">
  
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
        crossorigin="anonymous">
  
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, 
        then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity=
"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity=
"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity=
"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous">
    </script>
      
    <title>
        How to automatically close all
        collapsible elements inside of 
        the accordion when closing the
        accordion?
    </title>
</head>
  
<body>
    <center>
        <h4><a class="text-success" 
            style="text-decoration: none;" href="#">
                Geeksforgeeks
            </a>
        </h4><br>
          
        <a class="text-success" data-toggle="collapse"
            href="#collapseExample" aria-expanded="false"
            aria-controls="collapseExample">
            Connect with href
        </a>
        <br /><br />
          
        <button class="btn btn-success" type="button"
                data-toggle="collapse" 
                data-target="#collapseExample"
                aria-expanded="false" 
                aria-controls="collapseExample">
            Button with data-target
        </button>
  
        <div class="collapse" id="collapseExample">
            <div class="card card-body">
                <h5 class="card-title">
                    Basic Example
                </h5>
  
                  
                <p>
                    Collapse plugin provides a quick 
                    way of revealing and hiding content.
                    It toggle the visibility of content
                    across your program project with a
                    few classes and Bootstrap4
                    JavaScript plugins.
                </p>
  
            </div>
        </div>
    </center>
</body>
  
</html>

** Nota : aquí el contenido se coloca en el centro si no lo desea, elimine la etiqueta <center>.

Múltiples elementos <button> o <a> pueden mostrar u ocultar el componente en caso de que hagan referencia a él con su atributo href o data-target . los

HTML

<!doctype html>
<html lang="en">
  
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,
            initial-scale=1, shrink-to-fit=no">
  
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
        crossorigin="anonymous">
  
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, 
         then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity=
"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity=
"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity=
"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous">
    </script>
      
    <title>Multiple Collapse</title>
</head>
  
<body>
    <center>
        <h4><a class="text-success" 
            style="text-decoration: none;" href="#">
                Geeksforgeeks
            </a>
        </h4><br>
          
        <a class="text-success" data-toggle="collapse" 
            href="#multiCollapseExample1" 
            aria-expanded="false"
            aria-controls="multiCollapseExample1">
            Flip first card
        </a>
          
        <button class="btn btn-success" type="button" 
            data-toggle="collapse" 
            data-target="#multiCollapseExample2"
            aria-expanded="false" 
            aria-controls="multiCollapseExample2">
            Flip second card
        </button>
  
        <button class="btn btn-success" type="button" 
            data-toggle="collapse" 
            data-target=".multi-collapse"
            aria-expanded="false" 
            aria-controls="multiCollapseExample1
                multiCollapseExample2">
            Flip third card
        </button>
          
        <div class="row">
            <div class="col">
                <div class="collapse multi-collapse" 
                    id="multiCollapseExample1">
                    <div class="card card-body text-success">
                        <h5 class="card-title">
                            Multiple collapse
                        </h5>
                        Collapse plugin provides a quick 
                        way of revealing and hiding content.
                        It toggle the visibility of content 
                        across your program project with a 
                        few classes and Bootstrap4 JavaScript
                        plugins.
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="collapse multi-collapse" 
                        id="multiCollapseExample2">
                    <div class="card card-body text-success">
                        <h5 class="card-title">
                            Multiple collapse
                        </h5>
                        Collapse plugin provides a quick way 
                        of revealing and hiding content.
                        It toggle the visibility of content 
                        across your program project with a 
                        few classes and Bootstrap4 JavaScript 
                        plugins.
                    </div>
                </div>
            </div>
        </div>
    </center>
</body>
  
</html>

Utilizando el componente de la tarjeta , podrá extender el comportamiento de contracción predeterminado para formar un acordeón.

Ejemplo :

HTML

<!doctype html>
<html lang="en">
  
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,
            initial-scale=1, shrink-to-fit=no">
  
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
        crossorigin="anonymous">
  
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, 
        then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity=
"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity=
"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity=
"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous">
    </script>
      
    <title>Accordion</title>
</head>
  
<body>
    <center>
        <h4><a class="text-success" 
            style="text-decoration: none;" href="#">
                Geeksforgeeks
            </a>
        </h4><br>
          
        <div id="accordion">
            <div class="card">
                <div class="card-header text-white 
                    mb-3 bg-success" id="headingOne">
                    <h5 class="mb-0">
                        <button class="btn btn-success" 
                            data-toggle="collapse" 
                            data-target="#collapseOne"
                            aria-expanded="true" 
                            aria-controls="collapseOne">
                            #1MyCollapsible
                        </button>
                    </h5>
                </div>
                <div id="collapseOne" class="collapse show" 
                    aria-labelledby="headingOne" 
                    data-parent="#accordion">
                      
                    <div class="card-body">
                        <b>
                            Collapse plugin provides a 
                            quick way of revealing and 
                            hiding content. It toggle 
                            the visibility of content 
                            across your program project
                            with a few classes and
                            Bootstrap4 JavaScript plugins.
                            Using the card component, you 
                            can extend the default collapse
                            behavior to create an
                            accordion.
                        </b>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header text-white 
                    mb-3 bg-success" id="headingTwo">
                    <h5 class="mb-0">
                        <button class="btn btn-success collapsed"
                            data-toggle="collapse" 
                            data-target="#collapseTwo"
                            aria-expanded="false" 
                            aria-controls="collapseTwo">
                            #2MyCollapsible
                        </button>
                    </h5>
                </div>
                <div id="collapseTwo" class="collapse" 
                    aria-labelledby="headingTwo" 
                    data-parent="#accordion">
  
                    <div class="card-body">
                        <b>
                            Collapse plugin provides a quick 
                            way of revealing and hiding content.
                            It toggle the visibility of content 
                            across your program project with a 
                            few classes and Bootstrap4 JavaScript
                            plugins. Using the card component, 
                            you can extend the default collapse 
                            behavior to create an accordion.
                        </b>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header text-white 
                    mb-3 bg-success" id="headingThree">
                    <h5 class="mb-0">
                        <button class="btn btn-success collapsed" 
                            data-toggle="collapse" 
                            data-target="#collapseThree"
                            aria-expanded="false" 
                            aria-controls="collapseThree">
                            #3MyCollapsible
                        </button>
                    </h5>
                </div>
                <div id="collapseThree" class="collapse" 
                    aria-labelledby="headingThree" 
                    data-parent="#accordion">
  
                    <div class="card-body">
                        <b>
                            Collapse plugin provides a quick 
                            way of revealing and hiding content.
                            It toggle the visibility of content
                            across your program project with a 
                            few classes and Bootstrap4 JavaScript
                            plugins. Using the card component, 
                            you can extend the default collapse 
                            behavior to create an accordion.
                        </b>
                    </div>
                </div>
            </div>
        </div>
    </center>
</body>
  
</html>

HTML

<!doctype html>
<html lang="en">
  
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,
            initial-scale=1, shrink-to-fit=no">
  
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity=
"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
        crossorigin="anonymous">
  
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, 
        then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity=
"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous">
    </script>
      
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity=
"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous">
    </script>
      
    <script src=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity=
"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous">
    </script>
    <title>Accordion</title>
</head>
  
<body>
    <center>
        <h4><a class="text-success" 
            style="text-decoration: none;" href="#">
                Geeksforgeeks
            </a>
        </h4><br>
          
        <div id="accordion">
            <div class="card">
                <div class="card-header text-white 
                    mb-3 bg-success" id="headingOne">
                    <h5 class="mb-0">
                        <button class="btn btn-success" 
                            data-toggle="collapse" 
                            data-target="#collapseOne"
                            aria-expanded="true" 
                            aria-controls="collapseOne">
                            #1MyCollapsible
                        </button>
                    </h5>
                </div>
                <div id="collapseOne" 
                    class="main collapse show" 
                    aria-labelledby="headingOne" 
                    data-parent="#accordion">
  
                    <div class="card-body">
                        <div id="accordionRecommendation">
                            <div class="card-header border 
                                text-white mb-3 bg-success" 
                                id="headingRecommendation">
  
                                <h5 class="mb-0">
                                    <button class=
                                        "btn btn-success collapsed" 
                                        data-toggle="collapse"
                                        data-target="#collapseOne1" 
                                        aria-expanded="false" 
                                        aria-controls="collapseOne1">
                                        Inner #1MyCollapsible
                                    </button>
  
                                    <button class="btn btn-success 
                                        collapsed" data-toggle="collapse"
                                        data-target="#collapseTwo1"
                                        aria-expanded="false" 
                                        aria-controls="collapseTwo1">
                                        Inner #2MyCollapsible
                                    </button>
  
                                    <button class="btn btn-success 
                                        collapsed" data-toggle="collapse"
                                        data-target="#collapseThree1" 
                                        aria-expanded="false"
                                        aria-controls="collapseThree1">
                                        Inner #3MyCollapsible
                                    </button>
                                </h5>
                            </div>
  
                            <div class="karte">
                                <div id="collapseOne1" class="collapse" 
                                    aria-labelledby="headingRecommendation"
                                    data-parent="#accordionRecommendation">
                                    <div class="card-body">
                                        <b>Some Content of First One</b>
                                    </div>
                                </div>
                            </div>
  
                            <div class="karte">
                                <div id="collapseTwo1" class="collapse" 
                                    aria-labelledby="headingRecommendation"
                                    data-parent="#accordionRecommendation">
                                    <div class="card-body">
                                        <b>Some Content of First Two</b>
                                    </div>
                                </div>
                            </div>
  
                            <div class="karte">
                                <div id="collapseThree1" class="collapse"
                                    aria-labelledby="headingRecommendation"
                                    data-parent="#accordionRecommendation">
                                    <div class="card-body">
                                        <b>Some Content of First Three</b>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header text-white mb-3 
                        bg-success" id="headingTwo">
                    <h5 class="mb-0">
                        <button class="btn btn-success collapsed"
                            data-toggle="collapse" 
                            data-target="#collapseTwo"
                            aria-expanded="false" 
                            aria-controls="collapseTwo">
                            #2MyCollapsible
                        </button>
                    </h5>
                </div>
  
                <div id="collapseTwo" class="collapse" 
                    aria-labelledby="headingTwo" 
                    data-parent="#accordion">
  
                    <div class="card-body">
                        Collapse plugin provides a quick 
                        way of revealing and hiding content.
                        It toggle the visibility of content
                        across your program project with a 
                        few classes and Bootstrap4 JavaScript
                        plugins. Using the card component, 
                        you can extend the default collapse
                        behavior to create an accordion.
                    </div>
                </div>
            </div>
  
            <div class="card">
                <div class="card-header text-white 
                    mb-3 bg-success" id="headingThree">
                    <h5 class="mb-0">
                        <button class="btn btn-success
                            collapsed" data-toggle="collapse"
                            data-target="#collapseThree"
                            aria-expanded="false" 
                            aria-controls="collapseThree">
                            #3MyCollapsible
                        </button>
                    </h5>
                </div>
                <div id="collapseThree" class="collapse" 
                    aria-labelledby="headingThree" 
                    data-parent="#accordion">
  
                    <div class="card-body">
                        Collapse plugin provides a quick 
                        way of revealing and hiding content.
                        It toggle the visibility of content
                        across your program project with a 
                        few classes and Bootstrap4 JavaScript
                        plugins. Using the card component, 
                        you can extend the default collapse 
                        behavior to create an accordion.
                    </div>
                </div>
            </div>
        </div>
    </center>
</body>
  
</html>

Agregue aria-expandida al componente de control. Esta cualidad transmite inequívocamente (explícitamente) el estado actual del componente plegable vinculado al control a los lectores de pantalla (lectores) y tecnologías de asistencia comparables. Si el elemento plegable está cerrado de forma predeterminada, la propiedad del elemento de control debe tener un valor de (set) aria-expanded=”false” . Si ha configurado el elemento plegable para que se abra de forma predeterminada utilizando la clase show, configure aria-expanded=”true”en el empeine de control. En consecuencia, el complemento cambiará (alternará) este rasgo en el control en función de si el componente plegable se ha abierto o cerrado (por medio de JavaScript, o porque el cliente activó otro componente de control demasiado vinculado al mismo componente plegable). En caso de que el componente HTML del elemento de control no sea un botón (por ejemplo, <a> o <div>), el atributo role=”button” debe incluirse en el componente.

En caso de que su componente de control se centre en un solo componente contraíble, es decir, el atributo de destino de datos indica un selector de identificación, debe incluir el atributo aria-controls en el componente de control, que contiene la identificación del componente contraíble. . Los lectores de pantalla avanzados y los avances (tecnologías) de asistencia similares hacen uso de esta característica para brindar a los usuarios más rutas alternativas para explorar directamente el componente plegable en sí.

Podemos usar Collapse y Accordion a través de atributos de datos o mediante javascript. 

El complemento de colapso utiliza una serie de clases para manejar el levantamiento abrumador:

  • .collapse  cubre el contenido
  • .collapse.show  aparece el contenido
  • .collapsing  se incluye cuando comienza la transición y se elimina cuando finaliza.

Agregue data-toggle=”collapse” y un destino de datos al componente para asignar naturalmente el control de uno o más componentes contraíbles. El atributo de destino de datos reconoce un selector de CSS para aplicar el colapso. Esté fuera de toda duda para incluir el colapso de clase en el componente colapsable. Si desea que se abra de forma predeterminada, agregue la presentación de clase adicional.

Para agregar administración de recopilación similar a un acordeón a un rango plegable, agregue el atributo de información data-parent=”#selector”

$('.collapse').collapse()

Métodos:

  • .collapse(opciones): promulga su contenido como un componente contraíble. Reconoce un objeto de alternativas opcionales. Las opciones son padre y alternar. Ex. $(‘#myCollapsible’).collapse({alternar: falso})
  • .collapse(‘toggle’): voltea un componente colapsable para que aparezca o se cubra.
  • .collapse(‘show’): Aparece un componente colapsable.
  • .collapse(‘hide’): Cubre un componente colapsable.
  • .collapse(‘dispose’): Devasta el colapso de un componente.

Publicación traducida automáticamente

Artículo escrito por swapnitanerkar28 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *