in English

Поповери

Документація та приклади додавання спливаючих вікон Bootstrap, подібних до тих, що є в iOS, до будь-якого елемента на вашому сайті.

Огляд

Що потрібно знати під час використання плагіна Popover:

  • Popovers покладаються на сторонню бібліотеку Popper для позиціонування. Ви повинні включити popper.min.js перед bootstrap.js або використовувати bootstrap.bundle.min.js/ bootstrap.bundle.js, який містить Popper, щоб поповери працювали!
  • Поповерам потрібен плагін підказки як залежність.
  • Якщо ви створюєте наш JavaScript із вихідного коду, для цього потрібноutil.js .
  • Поповерси можна використовувати з міркувань продуктивності, тому ви повинні ініціалізувати їх самостійно .
  • Нульова довжина titleта contentзначення ніколи не показуватимуть спливаюче зображення.
  • Укажіть container: 'body', щоб уникнути проблем із відтворенням у більш складних компонентах (як-от наші групи вводу, групи кнопок тощо).
  • Запуск спливаючих вікон на прихованих елементах не працюватиме.
  • Поповер для елементів .disabledабо має запускатися на елементі-оболонці.disabled
  • Коли запускаються з прив’язок, які перетинають кілька ліній, спливаючі елементи будуть зосереджені між загальною шириною прив’язок. Використовуйте .text-nowrapна вашому <a>s, щоб уникнути такої поведінки.
  • Поповери мають бути приховані до того, як їхні відповідні елементи будуть видалені з DOM.
  • Поповер можна активувати завдяки елементу в тіньовому DOM.
За замовчуванням цей компонент використовує вбудований засіб очищення вмісту, який видаляє будь-які елементи HTML, які явно не дозволені. Щоб отримати докладніші відомості , перегляньте розділ дезінфікуючого засобу в нашій документації JavaScript .
Ефект анімації цього компонента залежить від prefers-reduced-motionмедіа-запиту. Перегляньте розділ про обмежений рух нашої документації щодо спеціальних можливостей .

Продовжуйте читати, щоб побачити, як працюють спливаючі кнопки з деякими прикладами.

Приклад: увімкніть спливаючі вікна всюди

Одним із способів ініціалізації всіх спливаючих вікон на сторінці є вибір їх за data-toggleатрибутом:

$(function () {
  $('[data-toggle="popover"]').popover()
})

Приклад: використання containerопції

Якщо у вашому батьківському елементі є деякі стилі, які заважають спливаючому вікну, ви захочете вказати настроюваний container, щоб HTML-код спливаючого елемента з’являвся в цьому елементі.

$(function () {
  $('.example-popover').popover({
    container: 'body'
  })
})

приклад

<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>

Чотири напрямки

Доступні чотири варіанти: вирівнювання вгорі, праворуч, внизу та ліворуч.

<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="top" data-content="Top popover">
  Popover on top
</button>
<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="right" data-content="Right popover">
  Popover on right
</button>
<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Bottom popover">
  Popover on bottom
</button>
<button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="left" data-content="Left popover">
  Popover on left
</button>

Відхилити після наступного натискання

Використовуйте focusтригер, щоб закрити спливаючі вікна під час наступного натискання користувачем іншого елемента, ніж елемент перемикання.

Спеціальна розмітка потрібна для відхилення при наступному клацанні

Для належної поведінки між браузерами та платформами ви повинні використовувати <a>тег, а не<button> тег, і ви також повинні включити tabindexатрибут.

<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover</a>
$('.popover-dismiss').popover({
  trigger: 'focus'
})

Відключені елементи

Елементи з disabledатрибутом не є інтерактивними, тобто користувачі не можуть наводити курсор або клацати на них, щоб викликати спливаюче вікно (або спливаючу підказку). Як обхідний шлях, ви захочете запустити спливаюче вікно з обгортки <div>або <span>перевизначити pointer-eventsвимкнений елемент.

Для вимкнених тригерів спливаючого вікна ви також можете віддати перевагу data-trigger="hover"тому, щоб спливаюче вікно з’являлося як негайний візуальний зворотний зв’язок для ваших користувачів, оскільки вони можуть не очікувати клацання вимкненого елемента.

<span class="d-inline-block" data-toggle="popover" data-content="Disabled popover">
  <button class="btn btn-primary" style="pointer-events: none;" type="button" disabled>Disabled button</button>
</span>

Використання

Увімкнути спливаючі вікна через JavaScript:

$('#example').popover(options)
Прискорення GPU

На пристроях з Windows 10 спливаючі зображення іноді виглядають розмитими через прискорення GPU та змінену роздільну здатність системи. Обхідним шляхом у версії 4 є вимкнути прискорення GPU за потреби на ваших спливаючих вікнах.

Пропоноване виправлення:

Popper.Defaults.modifiers.computeStyle.gpuAcceleration = !(window.devicePixelRatio < 1.5 && /Win/.test(navigator.platform))

Зробіть так, щоб спливаючі кнопки працювали для користувачів клавіатури та допоміжних технологій

Щоб дозволити користувачам клавіатури активувати ваші спливаючі елементи, ви повинні додавати їх лише до елементів HTML, які традиційно фокусуються клавіатурою та є інтерактивними (наприклад, посилання або елементи керування формою). Хоча довільні HTML-елементи (такі як <span>s) можна зробити доступними для фокусування, додавши tabindex="0"атрибут, це додасть потенційно дратівливі та заплутані позиції табуляції на неінтерактивних елементах для користувачів клавіатури, і більшість допоміжних технологій наразі не повідомляють вміст спливаючого вікна в цій ситуації . Крім того, не покладайтеся лише на hoverтригер для ваших спливаючих повернень, оскільки це унеможливить їх ініціювання для користувачів клавіатури.

Хоча ви можете вставляти насичений, структурований HTML у спливаючих вікнах за допомогою цієї htmlопції, ми настійно рекомендуємо вам уникати додавання надмірної кількості вмісту. Те, як спливаючі елементи зараз працюють, полягає в тому, що після відображення їхній вміст прив’язується до тригерного елемента за допомогою aria-describedbyатрибута. У результаті весь вміст popover буде оголошено користувачам допоміжних технологій як один довгий безперервний потік.

Крім того, хоча можна також включити інтерактивні елементи керування (такі як елементи форми або посилання) у ваш спливаюче вікно (шляхом додавання цих елементів до whiteListабо дозволених атрибутів і тегів), майте на увазі, що наразі спливне вікно не керує порядком фокусування клавіатури. Коли користувач клавіатури відкриває спливаюче вікно, фокус залишається на елементі запуску, і оскільки спливаюче вікно зазвичай не слідує відразу за тригером у структурі документа, немає гарантії, що переміщення вперед/натисканняTABперемістить користувача клавіатури до самого спливаючого вікна. Коротше кажучи, просте додавання інтерактивних елементів керування до спливаючого вікна, ймовірно, зробить ці елементи керування недоступними/непридатними для користувачів клавіатури та допоміжних технологій або, принаймні, призведе до нелогічного загального порядку фокусування. У таких випадках краще використовувати модальне діалогове вікно.

Опції

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

Note that for security reasons the sanitize, sanitizeFn and whiteList options cannot be supplied using data attributes.
Name Type Default Description
animation boolean true Apply a CSS fade transition to the popover
container string | element | false false

Appends the popover to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the popover in the flow of the document near the triggering element - which will prevent the popover from floating away from the triggering element during a window resize.

content string | element | function ''

Default content value if data-content attribute isn't present.

If a function is given, it will be called with its this reference set to the element that the popover is attached to.

delay number | object 0

Delay showing and hiding the popover (ms) - does not apply to manual trigger type

If a number is supplied, delay is applied to both hide/show

Object structure is: delay: { "show": 500, "hide": 100 }

html boolean false Insert HTML into the popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
placement string | function 'right'

How to position the popover - auto | top | bottom | left | right.
When auto is specified, it will dynamically reorient the popover.

When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the popover instance.

selector string | false false If a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have popovers added. See this and an informative example.
template string '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'

Base HTML to use when creating the popover.

The popover's title will be injected into the .popover-header.

The popover's content will be injected into the .popover-body.

.arrow will become the popover's arrow.

The outermost wrapper element should have the .popover class.

title string | element | function ''

Default title value if title attribute isn't present.

If a function is given, it will be called with its this reference set to the element that the popover is attached to.

trigger string 'click' How popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space. manual cannot be combined with any other trigger.
offset number | string 0 Offset of the popover relative to its target. For more information refer to Popper's offset docs.
fallbackPlacement string | array 'flip' Allow to specify which position Popper will use on fallback. For more information refer to Popper's behavior docs
customClass string | function ''

Add classes to the popover when it is shown. Note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces: 'a b'.

You can also pass a function that should return a single string containing additional class names.

boundary string | element 'scrollParent' Overflow constraint boundary of the popover. Accepts the values of 'viewport', 'window', 'scrollParent', or an HTMLElement reference (JavaScript only). For more information refer to Popper's preventOverflow docs.
sanitize boolean true Enable or disable the sanitization. If activated 'template', 'content' and 'title' options will be sanitized. See the sanitizer section in our JavaScript documentation.
whiteList object Default value Object which contains allowed attributes and tags
sanitizeFn null | function null Here you can supply your own sanitize function. This can be useful if you prefer to use a dedicated library to perform sanitization.
popperConfig null | object null To change Bootstrap's default Popper config, see Popper's configuration

Data attributes for individual popovers

Options for individual popovers can alternatively be specified through the use of data attributes, as explained above.

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.

See our JavaScript documentation for more information.

$().popover(options)

Initializes popovers for an element collection.

.popover('show')

Reveals an element’s popover. Returns to the caller before the popover has actually been shown (i.e. before the shown.bs.popover event occurs). This is considered a “manual” triggering of the popover. Popovers whose title and content are both zero-length are never displayed.

$('#element').popover('show')

.popover('hide')

Hides an element’s popover. Returns to the caller before the popover has actually been hidden (i.e. before the hidden.bs.popover event occurs). This is considered a “manual” triggering of the popover.

$('#element').popover('hide')

.popover('toggle')

Toggles an element’s popover. Returns to the caller before the popover has actually been shown or hidden (i.e. before the shown.bs.popover or hidden.bs.popover event occurs). This is considered a “manual” triggering of the popover.

$('#element').popover('toggle')

.popover('dispose')

Hides and destroys an element’s popover. Popovers that use delegation (which are created using the selector option) cannot be individually destroyed on descendant trigger elements.

$('#element').popover('dispose')

.popover('enable')

Gives an element’s popover the ability to be shown. Popovers are enabled by default.

$('#element').popover('enable')

.popover('disable')

Removes the ability for an element’s popover to be shown. The popover will only be able to be shown if it is re-enabled.

$('#element').popover('disable')

.popover('toggleEnabled')

Toggles the ability for an element’s popover to be shown or hidden.

$('#element').popover('toggleEnabled')

.popover('update')

Updates the position of an element’s popover.

$('#element').popover('update')

Events

Event Type Description
show.bs.popover This event fires immediately when the show instance method is called.
shown.bs.popover This event is fired when the popover has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.popover This event is fired immediately when the hide instance method has been called.
hidden.bs.popover This event is fired when the popover has finished being hidden from the user (will wait for CSS transitions to complete).
inserted.bs.popover Ця подія запускається після show.bs.popoverподії, коли шаблон спливаючого зображення було додано до DOM.
$('#myPopover').on('hidden.bs.popover', function () {
  // do something...
})