Collapse

Accessibility

Be sure to add to the control element. This attribute explicitly conveys the current state of the collapsible element tied to the control to screen readers and similar assistive technologies. If the collapsible element is closed by default, the attribute on the control element should have a value of . If you’ve set the collapsible element to be open by default using the class, set on the control instead. The plugin will automatically toggle this attribute on the control based on whether or not the collapsible element has been opened or closed (via JavaScript, or because the user triggered another control element also tied to the same collapsbile element). If the control element’s HTML element is not a button (e.g., an or ), the attribute should be added to the element.

If your control element is targeting a single collapsible element – i.e. the attribute is pointing to an selector – you should add the attribute to the control element, containing the of the collapsible element. Modern screen readers and similar assistive technologies make use of this attribute to provide users with additional shortcuts to navigate directly to the collapsible element itself.

Note that Bootstrap’s current implementation does not cover the various keyboard interactions described in the — you will need to include these yourself with custom JavaScript.

Usage

The collapse plugin utilizes a few classes to handle the heavy lifting:

  • hides the content
  • shows the content
  • is added when the transition starts, and removed when it finishes

These classes can be found in .

Via data attributes

Just add and a to the element to automatically assign control of one or more collapsible elements. The attribute accepts a CSS selector to apply the collapse to. Be sure to add the class to the collapsible element. If you’d like it to default open, add the additional class .

To add accordion-like group management to a collapsible area, add the data attribute . Refer to the demo to see this in action.

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to , as in .

Name Type Default Description
parent selector | jQuery object | DOM element false If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior — this is dependent on the class). The attribute has to be set on the target collapsible area.
toggle boolean true Toggles the collapsible element on invocation

Methods

Asynchronous methods and transitions

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.

Activates your content as a collapsible element. Accepts an optional options .

Toggles a collapsible element to shown or hidden. Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the or event occurs).

Shows a collapsible element. Returns to the caller before the collapsible element has actually been shown (i.e. before the event occurs).

Hides a collapsible element. Returns to the caller before the collapsible element has actually been hidden (i.e. before the event occurs).

Destroys an element’s collapse.

Event Type Description
show.bs.collapse This event fires immediately when the instance method is called.
shown.bs.collapse This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.collapse This event is fired immediately when the method has been called.
hidden.bs.collapse This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).

Взаимодействие со множественными объектами

Кнопки и ссылки и могут показывать и прятать сразу несколько элементов, обращаясь к их атрибутам или через селектор jQuery. Несколько или могут показывать или прятать один элемент, если каждый из них обращается к элементу через свои атрибуты или .

Toggle second element
Toggle both elements

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Create A Collapsible

Step 1) Add HTML:

<button type=»button» class=»collapsible»>Open Collapsible</button><div class=»content»> 
<p>Lorem ipsum…</p></div>

Step 2) Add CSS:

Style the accordion:

/* Style the button that is used to open and close the
collapsible content */.collapsible {  background-color: #eee; 
color: #444;  cursor: pointer;  padding: 18px; 
width: 100%;  border: none;  text-align: left; 
outline: none;  font-size: 15px;}/* Add a background color to the button if it is clicked on (add the
.active class with JS), and when you move the mouse over it (hover) */
.active, .collapsible:hover {  background-color: #ccc;}/* Style the
collapsible content. Note:
hidden by default */.content {  padding: 0 18px;  display:
none;  overflow: hidden;  background-color: #f1f1f1;}

Step 3) Add JavaScript:

var coll = document.getElementsByClassName(«collapsible»);var i;
for (i = 0; i < coll.length; i++) {  coll.addEventListener(«click»,
function() {    this.classList.toggle(«active»);   
var content = this.nextElementSibling;    if (content.style.display
=== «block») {      content.style.display =
«none»;    } else {     
content.style.display = «block»;    }  });}

Использование

Плагин «скрытия\показа» использует несколько классов для работы c даже «тяжелыми» элементами:

  • прячет содержимое
  • показывает содержимое
  • добавляется, когда переход начинается и удаляется с его завершением

Эти классы можно найти в .

Через атрибуты

Добавьте в элемент атрибуты и для автоматического контроля одного или более скрываемых элементов. Атрибут принимает CSS-селектор для применения к нему поведения toggle’a. Удостоверьтесь, что добавили в скрываемый элемент класс . Если он должен быть показан по умолчанию, добавьте в него класс .

Для добавления компактно расположенной (см. Разворачиваемые панели для экономии места) группы «контролирующих» элементов добавьте атрибут . Обратитесь к демо для просмотра в действии.

Параметры

Параметры можно передавать через атрибуты или JavaScript. Чтобы сделать это через атрибуты, добавьте имя параметра к , например .

Имя Тип По умолч. Описание
parent selector | jQuery object | DOM element false Если есть родительский элемент, все скрываемые элементы под определенным «родителем» закроются, когда он открыт (как в «аккордеоне» — это зависит от класса ). Атрибут нужно устанавливать в скрываемой зоне.
toggle boolean true Взаимодействует с скрываемым элементом по обращению

Методы

Асинхронные методы и переходы

Все методы API асинхронны и запускают переход. Они возвращаются функции, вызвавшей их, с началом перехода, но до его конца. Плюс, вызов метода к компоненту, выполняющему переход, будет проигнорирован.

Задействует ваше содержимое как скрываемый элемент. Принимает дополнительных опций.

Задействует на скрываемом элементе функциональность toggle’а (hide\show). Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки событий или event occurs).

Показывает скрываемый элемент. Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки события ).

Прячет скрываемый элемент. Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки события ).

Уничтожает «коллпас» элемента.

События

Класс «коллапса» в Bootstrap содержит несколько событий для вовлечения, взаимодействия и связи иных событий JS с функциональностью «коллапса».

Тип события Описание
show.bs.collapse Это событие наступает немедленно по вызову экземпляра метода .
shown.bs.collapse Это событие наступает, когда элемент «коллапса» сделан видимым юзеру (будет ждать выполнения CSS-переходов).
hide.bs.collapse Это событие наступает немедленно по вызову метода .
hidden.bs.collapse Это событие наступает как только элемент «коллапса» скрыт от юзера (будет ждать выполнения CSS-переходов).

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

Multiple targets

A or can show and hide multiple elements by referencing them with a JQuery selector in its or attribute.
Multiple or can show and hide an element if they each reference it with their or attribute

Toggle second element
Toggle both elements

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Доступность

Добавьте к «контролирующему» элементу. Этот атрибут явно передает текущее состояние скрываемого элемента, привязанного к «контролирующему» элементу, «экранным читалкам» и прочим вспомогательным технологиям. Если скрываемый элемент скрыт по умолчанию, его aria-expanded должен быть «false» . Если раньше вы определяли скрываемый элемент показываемым по умолчанию через класс , теперь используйте вместо этого класса в «контролирующем» элементе. Основываясь на том, показан или скрыт элемент, плагин будет автоматически переключать этот атрибут (через JavaScript либо через отслеживание клика по другому «контролирующему» элементу, связанному с данным скрываемым элементом). If the control element’s HTML element is not a button (e.g., an or ), the attribute should be added to the element.

Дополнение: если ваш «контролирующий» элемент взаимодействует с одним скрываемым элементом – т.е. атрибут указывает на # – вы можете добавить дополнительный атрибут к «контролирующему» элементу, содержащему # этого скрываемого элемента.

Заметим, что текущая версия Bootstrap не работает с различными событиями взаимодействия с клавиатурой, описанными в — и вам потребуется подключить эти события с помощью обычного JavaScript.

Несколько целей

A и может отображать и скрывать несколько элементов, ссылаясь на них с помощью селектора в своем атрибуте и . Несколько или могут отображать и скрывать элемент, если каждый из них ссылается на него с помощью своего атрибута или

Toggle second element
Toggle both elements

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Доступность

Не забудьте добавить элементу управления. Этот атрибут однозначно определяет ток состояние сборного элемента на экране читателей и подобных вспомогательных технологий. Если складной элемент закрыт по умолчанию, он должен иметь значение . Если вы установите складной элемент, который будет открыт по умолчанию, используя класс, набор , а не на контроль. Плагин будет автоматически переключаться на этот атрибут, если не разборный элемент был открыт или закрыт.

Кроме того, если элемент ориентирован на один складной элемент, т. е. атрибут, указывающий на селектор – можно добавить дополнительные атрибут в элемент, содержащий складной элемент. Современные читатели экраном и подобных вспомогательных технологий используйте этот атрибут, чтобы предоставить пользователям дополнительные клавиши, чтобы перейти непосредственно к самой складной элемент.

More Examples

Example

<button type=»button» class=»btn btn-info» data-toggle=»collapse» data-target=»#demo»>  Simple collapsible</button><div id=»demo» class=»collapse in»>  Lorem ipsum dolor sit amet, consectetur adipisicing elit,  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.  Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris  nisi ut aliquip ex ea commodo consequat.
</div>

Example

<div class=»panel-group»>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» href=»#collapse1″>Collapsible panel</a>      </h4>    </div>    <div id=»collapse1″ class=»panel-collapse collapse»>      <div class=»panel-body»>Panel Body</div>      <div class=»panel-footer»>Panel Footer</div>    </div>  </div></div>

Example

<div class=»panel-group»>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» href=»#collapse1″>Collapsible list group</a>      </h4>    </div>    <div id=»collapse1″ class=»panel-collapse collapse»>      <ul class=»list-group»>        <li class=»list-group-item«>One</li>        <li class=»list-group-item»>Two</li>        <li class=»list-group-item»>Three</li>      </ul>      <div class=»panel-footer»>Footer</div>    </div>  </div></div>

Accordion

The following example shows a simple accordion by extending the panel component:

Note: The attribute makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.

Example

<div class=»panel-group» id=»accordion»>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse1″>        Collapsible Group 1</a>      </h4>    </div>    <div id=»collapse1″ class=»panel-collapse collapse in»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse2″>        Collapsible Group 2</a>      </h4>    </div>    <div id=»collapse2″ class=»panel-collapse collapse»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse3″>        Collapsible Group 3</a>      </h4>    </div>    <div id=»collapse3″ class=»panel-collapse collapse»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div></div>

Example

$(document).ready(function(){  $(«#demo»).on(«hide.bs.collapse», function(){    $(«.btn»).html(‘<span class=»glyphicon glyphicon-collapse-down»></span> Open’);  });  $(«#demo»).on(«show.bs.collapse», function(){    $(«.btn»).html(‘<span class=»glyphicon glyphicon-collapse-up»></span> Close’);  });
});

Or you can use CSS:

Example

/* Icon when the collapsible content is shown */.btn:after {  font-family: «Glyphicons Halflings»;  content: «\e114»;}/* Icon when the collapsible content is hidden */.btn.collapsed:after {  content: «\e080»;}

❮ Previous
Next ❯

Применение

Плагин collapse использует несколько классов для работы с тяжелой работой:

  • скрывает содержимое
  • показывает содержание
  • добавляется, когда переход начинается, и удаляется, когда он заканчивается

Эти классы можно найти в .

Через атрибуты данных

Просто добавьте и к элементу для автоматического назначения контроля одного или несколько складных элементов. Атрибут принимает селектор CSS , чтобы применить коллапс. Обязательно добавьте класс к складному элементу. Если вы хотите, чтобы он был открыт по умолчанию, добавьте дополнительный класс .

Чтобы добавить управление группами в виде гармошки в сворачиваемую область, добавьте атрибут данных . Обратитесь к демонстрации, чтобы увидеть это в действии.

Параметры

Параметры можно передавать через атрибуты данных или JavaScript. Для атрибутов данных добавьте имя параметра , как в .

имя Тип По умолчанию Описание
селектор | объект jQuery | Элемент DOM Если указан родительский элемент, все складные элементы в указанном родительском элементе будут закрыты при отображении этого складного элемента. (аналогично традиционному поведению аккордеона — это зависит от класса). Атрибут должен быть установлен в целевой складной области.
логический Переключает сворачиваемый элемент при вызове

Методы

Асинхронные методы и переходы

Все методы API асинхронны и запускают переход. Они возвращаются к вызывающему, как только переход начнется, но до его завершения. Кроме того, вызов метода переходного компонента будет проигнорирован .

Активирует ваш контент как складной элемент. Принимает необязательные параметры .

Вы можете создать экземпляр сворачивания с помощью конструктора, например:

Метод Описание
Переключает складной элемент на показанный или скрытый. Возврат к вызывающей стороне до того, как сворачиваемый элемент будет фактически показан или скрыт (то есть до того, как произойдет событие или ).
Показывает разборный элемент. Возврат к вызывающей стороне до того, как сворачиваемый элемент будет фактически показан (например, до того, как произойдет событие).
Скрывает разборный элемент. Возврат к вызывающей стороне до того, как складной элемент был фактически скрыт (например, до того, как произошло событие).
Разрушает обрушение элемента.
Статический метод, позволяющий получить экземпляр коллапса, связанный с элементом DOM.

События

Класс коллапса Bootstrap предоставляет несколько событий для подключения к функциональности коллапса.

Тип события Описание
Это событие срабатывает сразу после вызова метода экземпляра.
Это событие запускается, когда элемент сворачивания стал видимым для пользователя (будет ожидать завершения переходов CSS).
Это событие запускается сразу после вызова метода.
Это событие запускается, когда элемент свертывания был скрыт от пользователя (будет ждать завершения переходов CSS).

Комментарии для сайта Cackle

Использование

Плагин «скрытия\показа» использует несколько классов для работы c даже «тяжелыми» элементами:

  • прячет содержимое
  • показывает содержимое
  • добавляется, когда переход начинается и удаляется с его завершением

Эти классы можно найти в .

Через атрибуты

Добавьте в элемент атрибуты и для автоматического контроля одного или более скрываемых элементов. Атрибут принимает CSS-селектор для применения к нему поведения toggle’a. Удостоверьтесь, что добавили в скрываемый элемент класс . Если он должен быть показан по умолчанию, добавьте в него класс .

Для добавления компактно расположенной (см. Разворачиваемые панели для экономии места) группы «контролирующих» элементов добавьте атрибут . Обратитесь к демо для просмотра в действии.

Параметры

Параметры можно передавать через атрибуты или JavaScript. Чтобы сделать это через атрибуты, добавьте имя параметра к , например .

Имя Тип По умолч. Описание
parent selector | jQuery object | DOM element false Если есть родительский элемент, все скрываемые элементы под определенным «родителем» закроются, когда он открыт (как в «аккордеоне» — это зависит от класса ). Атрибут нужно устанавливать в скрываемой зоне.
toggle boolean true Взаимодействует с скрываемым элементом по обращению

Методы

Асинхронные методы и переходы

Все методы API асинхронны и запускают переход. Они возвращаются функции, вызвавшей их, с началом перехода, но до его конца. Плюс, вызов метода к компоненту, выполняющему переход, будет проигнорирован.

Активирует ваш контент с использованием разворачиваемых панелей. Принимает необязательный параметров.

Вы можете создать экземпляр сворачивания с помощью конструктора, например:

Метод Описание
Задействует на скрываемом элементе функциональность toggle’а (hide\show). Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки событий или event occurs).
Показывает скрываемый элемент. Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки события ).
Прячет скрываемый элемент. Возвращается к функции-вызову до того, как элемент показан или скрыт (т.е. до отработки события ).
Уничтожает «коллпас» элемента.
Статический метод, позволяющий получить экземпляр коллапса, связанный с элементом DOM.
Тип события Описание
show.bs.collapse Это событие наступает немедленно по вызову экземпляра метода .
shown.bs.collapse Это событие наступает, когда элемент «коллапса» сделан видимым юзеру (будет ждать выполнения CSS-переходов).
hide.bs.collapse Это событие наступает немедленно по вызову метода .
hidden.bs.collapse Это событие наступает как только элемент «коллапса» скрыт от юзера (будет ждать выполнения CSS-переходов).

Accordion

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

The following example shows a simple accordion by extending the panel component.

Note: Use the attribute to make
sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.

Example

<div class=»panel-group» id=»accordion»>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse1″>        Collapsible Group 1</a>      </h4>    </div>    <div id=»collapse1″ class=»panel-collapse collapse in»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse2″>        Collapsible Group 2</a>      </h4>    </div>    <div id=»collapse2″ class=»panel-collapse collapse»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div>  <div class=»panel panel-default»>    <div class=»panel-heading»>      <h4 class=»panel-title»>        <a data-toggle=»collapse» data-parent=»#accordion» href=»#collapse3″>        Collapsible Group 3</a>      </h4>    </div>    <div id=»collapse3″ class=»panel-collapse collapse»>      <div class=»panel-body»>Lorem ipsum dolor sit amet, consectetur adipisicing elit,      sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad      minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea      commodo consequat.</div>    </div>  </div></div>

Usage

The collapse plugin utilizes a few classes to handle the heavy lifting:

  • hides the content
  • shows the content
  • is added when the transition starts, and removed when it finishes

These classes can be found in .

Via data attributes

Just add and a to the element to automatically assign control of one or more collapsible elements. The attribute accepts a CSS selector to apply the collapse to. Be sure to add the class to the collapsible element. If you’d like it to default open, add the additional class .

To add accordion-like group management to a collapsible area, add the data attribute . Refer to the demo to see this in action.

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to , as in .

Name Type Default Description
parent selector | jQuery object | DOM element false If parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior — this is dependent on the class). The attribute has to be set on the target collapsible area.
toggle boolean true Toggles the collapsible element on invocation

Methods

Asynchronous methods and transitions

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.

Activates your content as a collapsible element. Accepts an optional options .

Toggles a collapsible element to shown or hidden. Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the or event occurs).

Shows a collapsible element. Returns to the caller before the collapsible element has actually been shown (i.e. before the event occurs).

Hides a collapsible element. Returns to the caller before the collapsible element has actually been hidden (i.e. before the event occurs).

Destroys an element’s collapse.

Event Type Description
show.bs.collapse This event fires immediately when the instance method is called.
shown.bs.collapse This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.collapse This event is fired immediately when the method has been called.
hidden.bs.collapse This event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).

Accessibility

Be sure to add to the control element. This attribute explicitly conveys the current state of the collapsible element tied to the control to screen readers and similar assistive technologies. If the collapsible element is closed by default, the attribute on the control element should have a value of . If you’ve set the collapsible element to be open by default using the class, set on the control instead. The plugin will automatically toggle this attribute on the control based on whether or not the collapsible element has been opened or closed (via JavaScript, or because the user triggered another control element also tied to the same collapsbile element). If the control element’s HTML element is not a button (e.g., an or ), the attribute should be added to the element.

If your control element is targeting a single collapsible element – i.e. the attribute is pointing to an selector – you should add the attribute to the control element, containing the of the collapsible element. Modern screen readers and similar assistive technologies make use of this attribute to provide users with additional shortcuts to navigate directly to the collapsible element itself.

Note that Bootstrap’s current implementation does not cover the various keyboard interactions described in the — you will need to include these yourself with custom JavaScript.

Animated Collapsible (Slide Down)

To make an animated collapsible, add , and
a for the max-height property, to
the class.

Then, use JavaScript to slide down the content by setting a calculated
, depending on the panel’s height on different screen sizes:

Example

<style>.content {  padding: 0 18px;  background-color: white;
 
max-height: 0;  overflow: hidden; 
transition: max-height 0.2s ease-out;}</style><script>var
coll =
document.getElementsByClassName(«collapsible»);var i;for (i = 0; i <
coll.length; i++) {  coll.addEventListener(«click», function() {    this.classList.toggle(«active»);
   
var content = this.nextElementSibling;    if (content.style.maxHeight){
     
content.style.maxHeight = null;    } else {     
content.style.maxHeight =
content.scrollHeight + «px»;    }   });}
</script>

Multiple targets

A or can show and hide multiple elements by referencing them with a JQuery selector in its or attribute.
Multiple or can show and hide an element if they each reference it with their or attribute

Toggle second element
Toggle both elements

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Multiple targets

A or can show and hide multiple elements by referencing them with a JQuery selector in its or attribute.
Multiple or can show and hide an element if they each reference it with their or attribute

Toggle second element
Toggle both elements

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector