Содержание
- 1 Под капотом: HTML и (S)CSS
- 2 Tooltips и основные сведения о всплывающих подсказках
- 3 Popover Builder Responsive jQuery Plugin
- 4 $ (selector, context).tooltip («action», [params]) Method
- 5 Props
- 6 Global options
- 7 Event Management on Tooltip elements
- 8 Создание всплывающих подсказок
- 9 Sass / Less
- 10 CSS
- 11 События плагина Tooltips
- 12 More
- 13 Creating an Arrow
- 14 Tooltip Options
Под капотом: HTML и (S)CSS
Для отображения подсказки к блочному или строчному элементу достаточно добавить атрибут , поэтому разметка HTML выглядит крайне тривиально:
В SCSS для удобства добавлено несколько переменных, которые можно настроить заранее, — это шрифт, цвет, эффект перехода и возможность сменить название атрибута:
Если внимательно проанализировать код, можно заметить правила и . Они необходимы, чтобы подсказка растягивалась вне зависимости от ширины родительского элемента, но при этом могла быть многострочной, а благодаря её максимальный размер не превышал трети текущего viewport.
Проблемы кроссбраузерности
Даже у такого незамысловатого способа реализации всплывающих подсказок есть некоторые проблемы с кроссбраузерностью, и речь идет вовсе не о древних браузерах. Так, например, Firefox испытывает явные трудности с определением размера строчного элемента, к которому добавляется псевдоэлемент, в результате чего позиционирование рассчитывается неверно и может «перескочить» на предыдущую строку:
В Firefox псевдоэлемент магическим образом способствует тому, что область содержимого строчного элемента на некоторых разрешениях экрана начинается от конца предыдущей строки.
Предотвратить недоразумение поможет правило для элемента, к которому добавляется tooltip. Однако это в свою очередь приведет к увеличению области его содержимого по вертикали и, следовательно, возрастёт расстояние между элементом и псевдоэлементами, поэтому целесообразно сократить отступ . С блочными элементами подобной проблемы не возникает:
Фактически, правило может быть применено к подсказкам абсолютно для всех браузеров, однако следует учитывать потенциальный конфликт стилей, если подсказка будет применяться к элементу с блочным, табличным и др. значением .
Другая менее значимая неприятность заключается в особенностях рендеринга текста, к которому была применена трансформация. Почти во всех браузерах наблюдается едва заметное изменение гарнитуры шрифта, приводящее к появлению и последующему удалению лишнего пикселя ширины, что создаёт эффект «мерцания» всего псевдоэлемента с текстом. Для устранения этого следует добавить дополнительную 3d-транформацию — так называемый хак для производительности и ещё пару полезных свойств:
По мимо прочего не все браузеры поддерживают относительные единицы измерения , , , и значения или для ширины элемента. В последнем случае это касается всех Internet Explorer и Edge, поэтому следует использовать строчную сетку, с помощью которой подсказка будет растягиваться по ширине контента, однако способа ограничить это максимальным значением не нашлось:
Tooltips и основные сведения о всплывающих подсказках
Всплывающая подсказка – это блок с некоторой информацией, появляющейся возле элемента при наведении на него курсора. Tooltips в Bootstrap могут быть добавлены к любым HTML элементам: (изображениям), (ссылкам), и др.
В Bootstrap 3 и 4 компонент Tooltips построен как с использованием стилей, так и кода на JavaScript.
Позиционирование всплывающей подсказки возле элемента в Bootstrap 3 осуществлялось собственным кодом. В Bootstrap 4 эта ситуация изменилась, теперь это осуществляется с использованием сторонней библиотеки «popper.js». Это означает что файл «bootstrap.js» зависит от «popper.js» и его нужно подключить перед ним.
Кроме этого варианта, можно ещё воспользоваться одним файлом «bootstrap.bundle.js». Данный файл включает уже включает в себя библиотеку «popper.js».
При самостоятельной сборке JavaScript из исходных кодов Bootstrap 4, для работы компонента Tooltips необходимо кроме файла «tooltips.js» в проект ещё включить «utils.js».
Popover Builder Responsive jQuery Plugin
December 24, 2018 | Bootstrap, Plugins
Popover Builder Responsive jQuery Plugin is a premium multi-purpose popover builder Plugin for Bootstrap and none Bootstrap sites. You can show content from other pages of the site easily like text, images etc. 50+ popular popovers designs are the part of this item. You can create your own popover design with the help of these pre-made designs.
Features:
- 50+ Pre-Built Popovers Designs
- 45+ Animation Effects
- PowerFul Builder To Build And Edit
- Import Content From Other Pages Of Your Site
- Import Content Dynamically Of Multiple Elements From Other Pages And Show This Content On Different Elements
- You Can Easily Export Popover Settings From One Website And Import To Another Website
- Animation Duration And Delay Ability
$ (selector, context).tooltip («action», [params]) Method
The tooltip (action, params) method can perform an action on the tooltip elements, such as disabling the tooltip. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action.
Syntax
$(selector, context).tooltip ("action", );
The following table lists the actions for this method −
Sr.No. | Action & Description |
---|---|
1 |
This action closes the tooltip. This method does not accept any arguments. |
2 |
This action removes the tooltip functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments. |
3 |
This action deactivates the tooltip. This method does not accept any arguments. |
4 |
This action activates the tooltip. This method does not accept any arguments. |
5 |
This action programmatically opens the tooltip. This method does not accept any arguments. |
6 |
This action gets the value associated with optionName for the tooltip. This method does not accept any arguments. |
7 |
This action gets an object containing key/value pairs representing the current tooltip options hash. This method does not accept any arguments. |
8 |
This action sets the value of the tooltip option associated with the specified optionName. |
9 |
This action sets one or more options for tooltip. |
10 |
This action returns a jQuery object containing the original element. This method does not accept any arguments. |
Examples
Now let us see an example using the actions from the above table. The following example demonstrates the use of actions disable and enable.
<!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $("#tooltip-8").tooltip({ //use 'of' to link the tooltip to your specified input position: { of: '#myInput', my: 'left center', at: 'left center' }, }), $('#myBtn').click(function () { $('#tooltip-8').tooltip("open"); }); }); </script> </head> <body style = "padding:100px;"> <!-- HTML --> <a id = "tooltip-8" title = "Message" href = "#"></a> <input id = "myInput" type = "text" name = "myInput" value = "0" size = "7" /> <input id = "myBtn" type = "submit" name = "myBtn" value = "myBtn" class = "myBtn" /> </body> </html>
Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
In the above example, click on myBtn button and a tooltip pops up.
Props
Name | Type | Default | Description |
---|---|---|---|
arrow | bool | false | If , adds an arrow to the tooltip. |
children* | element | Tooltip reference element.️ . | |
classes | object | Override or extend the styles applied to the component. See below for more details. | |
disableFocusListener | bool | false | Do not respond to focus events. |
disableHoverListener | bool | false | Do not respond to hover events. |
disableTouchListener | bool | false | Do not respond to long press touch events. |
enterDelay | number | 100 | The number of milliseconds to wait before showing the tooltip. This prop won’t impact the enter touch delay (). |
enterNextDelay | number | The number of milliseconds to wait before showing the tooltip when one was already recently opened. | |
enterTouchDelay | number | 700 | The number of milliseconds a user must touch the element before showing the tooltip. |
id | string | This prop is used to help implement the accessibility logic. If you don’t provide this prop. It falls back to a randomly generated id. | |
interactive | bool | false | Makes a tooltip interactive, i.e. will not close when the user hovers over the tooltip before the is expired. |
leaveDelay | number | The number of milliseconds to wait before hiding the tooltip. This prop won’t impact the leave touch delay (). | |
leaveTouchDelay | number | 1500 | The number of milliseconds after the user stops touching an element before hiding the tooltip. |
onClose | func | Callback fired when the component requests to be closed.Signature:event: The event source of the callback. | |
onOpen | func | Callback fired when the component requests to be open.Signature:event: The event source of the callback. | |
open | bool | If , the tooltip is shown. | |
placement | ‘bottom-end’| ‘bottom-start’| ‘bottom’| ‘left-end’| ‘left-start’| ‘left’| ‘right-end’| ‘right-start’| ‘right’| ‘top-end’| ‘top-start’| ‘top’ | ‘bottom’ | Tooltip placement. |
PopperComponent | elementType | Popper | The component used for the popper. |
PopperProps | object | Props applied to the element. | |
title* | node | Tooltip title. Zero-length titles string are never displayed. | |
TransitionComponent | elementType | Grow | The component used for the transition. to learn more about the requirements for this component. |
TransitionProps | object | Props applied to the element. |
The is forwarded to the root element.
Any other props supplied will be provided to the root element (native element).
Global options
The default global options are:
{ defaultPlacement'top', defaultClass'vue-tooltip-theme', defaultTargetClass'has-tooltip', defaultHtmltrue, defaultTemplate'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', defaultArrowSelector'.tooltip-arrow, .tooltip__arrow', defaultInnerSelector'.tooltip-inner, .tooltip__inner', defaultDelay, defaultTrigger'hover focus', defaultOffset, defaultContainer'body', defaultBoundariesElementundefined, defaultPopperOptions{}, defaultLoadingClass'tooltip-loading', defaultLoadingContent'...', autoHidetrue, defaultHideOnTargetClicktrue, disposeTimeout5000, popover{ defaultPlacement'bottom', defaultClass'vue-popover-theme', defaultBaseClass'tooltip popover', defaultWrapperClass'wrapper', defaultInnerClass'tooltip-inner popover-inner', defaultArrowClass'tooltip-arrow popover-arrow', defaultOpenClass'open', defaultDelay, defaultTrigger'click', defaultOffset, defaultContainer'body', defaultBoundariesElementundefined, defaultPopperOptions{}, defaultAutoHidetrue, defaultHandleResizetrue,},}
You can change the options during install with the arguments:
importVTooltipfrom'v-tooltip'Vue.use(VTooltip, options)
Or directly on package:
importVTooltipfrom'v-tooltip'VTooltip.options.defaultClass='my-tooltip'
Event Management on Tooltip elements
In addition to the tooltip (options) method which we saw in the previous sections, JqueryUI provides event methods as which gets triggered for a particular event. These event methods are listed below −
Sr.No. | Event Method & Description |
---|---|
1 |
Triggered when the tooltip is created. Where event is of type Event, and ui is of type Object. |
2 |
Triggered when the tooltip is closed. Usually triggers on focusout or mouseleave. Where event is of type Event, and ui is of type Object. |
3 |
Triggered when the tooltip is displayed or shown. Usually triggered on focusin or mouseover. Where event is of type Event, and ui is of type Object. |
Examples
The following example demonstrates event method usage during tooltip functionality. This example demonstrates use of open and close events.
<!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tooltip functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $('.tooltip-9').tooltip({ items: 'a.tooltip-9', content: 'Hello welcome…', show: "slideDown", // show immediately open: function(event, ui) { ui.tooltip.hover( function () { $(this).fadeTo("slow", 0.5); }); } }); }); $(function() { $('.tooltip-10').tooltip({ items: 'a.tooltip-10', content: 'Welcome to TutorialsPoint…', show: "fold", close: function(event, ui) { ui.tooltip.hover(function() { $(this).stop(true).fadeTo(500, 1); }, function() { $(this).fadeOut('500', function() { $(this).remove(); }); }); } }); }); </script> </head> <body style = "padding:100px;"> <!-- HTML --> <div id = "target"> <a href = "#" class = "tooltip-9">Hover over me!</a> <a href = "#" class = "tooltip-10">Hover over me too!</a> </div> </body> </html>
Let us save the above code in an HTML file tooltipexample.htm and open it in a standard browser which supports javascript, you must also see the following output −
In the above example the tooltip for Hover over me! disappear immediately whereas the tooltip for Hover over me too! fades out after duration of 1000ms.
Previous Page Print Page
Next Page
Создание всплывающих подсказок
Перед тем как переходить к созданию всплывающих подсказок для элементов необходимо рассмотреть некоторые особенности работы с ними:
- Всплывающие подсказки по соображениям производительности автоматически не инициализируются. Действие по инициализации необходимо выполнить дополнительно, например, после загрузки страницы.
- Всплывающие подсказки с пустым содержимым не отображаются.
- Установите параметру значение чтобы избежать проблем рендеринга этого компонента в более сложных компонентах (например, в input или button группах). В Bootstrap 4 данное значение параметр имеет по умолчанию.
- Всплывающие подсказки на скрытых элементах не работают.
- Всплывающая подсказка для не активного элемента (т.е. имеющего класс или атрибут ) должна вызываться на его родителе.
- При вызове Tooltips на гиперссылках, которые состоят из нескольких строк, всплывающие подсказки будут центрироваться. Используйте на элементе , чтобы отключить такое поведение.
- Всплывающие подсказки должны быть скрыты перед удалением соответствующих элементов из DOM.
Создание всплывающей подсказки осуществляется посредством добавления к HTML-элементу атрибута с необходимым сообщением.
<!-- Bootstrap 3 и 4 --> <button id="btn-tooltip" class="btn btn-danger" title="текст всплывающей подсказки">Кнопка с подсказкой</button>
После этого, чтобы всплывающая подсказка работала, её необходимо инициализировать.
Для этого нужно прописать в скрипт следующий код:
// выбираем соответствующий элемент и вызываем для него метод tooltip $('#btn-tooltip').tooltip();
В этом примере выбор элемента для которого нужно показывать tooltip осуществлялось по .
По умолчанию всплывающая подсказка располагается сверху от элемента.
Пример на Bootstrap 3 Пример на Bootstrap 4
Но если на странице много элементов, для которых нужно инициализировать всплывающую подсказку, то к ним нужно добавить какой-то опознавательный «знак», например, атрибут .
Затем в скрипте после загрузки DOM выбрать все эти элементы и вызвать для них метод .
<!-- Bootstrap 4 --> <a href="#" data-toggle="tooltip" title="текст подсказки">текст ссылки</a> ... <span data-toggle="tooltip" title="другой текст подсказки">некоторый текст</span> ... <script> // после загрузки страницы $(function(){ // инициализации подсказок для всех элементов на странице, имеющих атрибут data-toggle="tooltip" $('').tooltip(); }); </script>
Sass / Less
.tooltip{displayblock!important;z-index10000;.tooltip-inner{backgroundblack;colorwhite;border-radius16px;padding5px10px4px;}.tooltip-arrow{width;height;border-stylesolid;positionabsolute;margin5px;border-colorblack;z-index1;}&x-placement^="top"{margin-bottom5px;.tooltip-arrow{border-width5px5px5px;border-left-colortransparent!important;border-right-colortransparent!important;border-bottom-colortransparent!important;bottom-5px;left calc(50%-5px);margin-top;margin-bottom;}}&x-placement^="bottom"{margin-top5px;.tooltip-arrow{border-width5px5px5px;border-left-colortransparent!important;border-right-colortransparent!important;border-top-colortransparent!important;top-5px;left calc(50%-5px);margin-top;margin-bottom;}}&x-placement^="right"{margin-left5px;.tooltip-arrow{border-width5px5px5px;border-left-colortransparent!important;border-top-colortransparent!important;border-bottom-colortransparent!important;left-5px;top calc(50%-5px);margin-left;margin-right;}}&x-placement^="left"{margin-right5px;.tooltip-arrow{border-width5px5px5px;border-top-colortransparent!important;border-right-colortransparent!important;border-bottom-colortransparent!important;right-5px;top calc(50%-5px);margin-left;margin-right;}}&.popover{$color#f9f9f9;.popover-inner{background$color;colorblack;padding24px;border-radius5px;box-shadow5px30pxrgba(black, .1);}.popover-arrow{border-color$color;}}&aria-hidden='true'{visibilityhidden;opacity;transitionopacity.15s, visibility .15s;}&aria-hidden='false'{visibilityvisible;opacity1;transitionopacity.15s;}}
CSS
Rule name | Global class | Description |
---|---|---|
popper | .MuiTooltip-popper | Styles applied to the Popper component. |
popperInteractive | .MuiTooltip-popperInteractive | Styles applied to the Popper component if . |
popperArrow | .MuiTooltip-popperArrow | Styles applied to the Popper component if . |
tooltip | .MuiTooltip-tooltip | Styles applied to the tooltip (label wrapper) element. |
tooltipArrow | .MuiTooltip-tooltipArrow | Styles applied to the tooltip (label wrapper) element if . |
arrow | .MuiTooltip-arrow | Styles applied to the arrow element. |
touch | .MuiTooltip-touch | Styles applied to the tooltip (label wrapper) element if the tooltip is opened by touch. |
tooltipPlacementLeft | .MuiTooltip-tooltipPlacementLeft | Styles applied to the tooltip (label wrapper) element if contains «left». |
tooltipPlacementRight | .MuiTooltip-tooltipPlacementRight | Styles applied to the tooltip (label wrapper) element if contains «right». |
tooltipPlacementTop | .MuiTooltip-tooltipPlacementTop | Styles applied to the tooltip (label wrapper) element if contains «top». |
tooltipPlacementBottom | .MuiTooltip-tooltipPlacementBottom | Styles applied to the tooltip (label wrapper) element if contains «bottom». |
You can override the style of the component thanks to one of these customization points:
- With a rule name of the .
- With a .
- With a theme and an .
If that’s not sufficient, you can check the implementation of the component for more detail.
События плагина Tooltips
JS Tooltips генерирует для всплывающих подсказок пять событий.
Имя | Описание |
---|---|
show.bs.tooltip | Событие возникает после вызова метода . |
shown.bs.tooltip | Это событие генерируется, когда подсказка становится полностью видимой пользователю (после завершения CSS переходов). |
hide.bs.tooltip | Событие возникает после вызова метода . |
hidden.bs.tooltip | Это событие генерируется, когда подсказка становится полностью скрытой от пользователя (после завершения CSS переходов). |
inserted.bs.tooltip | Это событие вызывается после события show.bs.tooltip, когда шаблон подсказки будет добавлен в DOM. |
Пример работы с событиями (при возникновении события выведем имя события, и время когда оно произошло):
<!-- Bootstrap 4 --> <div class="row"> <div class="col-4 text-center"> <button class="btn btn-danger" data-toggle="tooltip" data-placement="top" title="текст всплывающей подсказки"> Кнопка с tooltip </button> </div> <div class="col-6"> <ul class="log text-left" style="height: 200px; overflow-y: auto;"></ul> </div> </div> ... <script> $(function () { $('').tooltip(); var t = function () { var now = new Date(); var m = now.getMinutes(); var s = now.getSeconds(); if (m < 10) m = '0' + m; if (s < 10) s = '0' + s; return m + ':' + s; }; $('').on('show.bs.tooltip', function () { $('.log').prepend('<li>' + t() + ' - show.bs.tooltip</li>'); }); $('').on('shown.bs.tooltip', function () { $('.log').prepend('<li>' + t() + ' - shown.bs.tooltip</li>'); }); $('').on('hide.bs.tooltip', function () { $('.log').prepend('<li>' + t() + ' - hide.bs.tooltip</li>'); }); $('').on('hidden.bs.tooltip', function () { $('.log').prepend('<li>' + t() + ' - hidden.bs.tooltip</li>'); }); $('').on('inserted.bs.tooltip', function () { $('.log').prepend('<li>' + t() + ' - inserted.bs.tooltip</li>'); }); }); </script>
More
Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements
Creating an Arrow
You can create arrows for your tooltips in CSS by combining the pseudo-element with an empty property. As a result, the tooltip resembles a speech bubble.
Example Copy
The example above follows these steps to create an arrow for a tooltip positioned on the bottom:
- There are no unique properties for creating arrows for tooltips. Therefore, we will use the border property.
- We need to position the arrow at the bottom by setting .
- The part of code centers the tooltip.
- The sets the size of the arrow. If you change the size, you also need to modify the to keep the arrow centered.
- The sets the color of the arrow. You should only define the top border and leave other borders transparent.
- You must set the to define the way the border looks. The example uses the value.
The following example shows how you create an arrow for the tooltip positioned at the top:
Example Copy
The below example demonstrates how you can add an arrow to the tooltip on the left side:
Example Copy
The below example shows how you can add an arrow to the tooltip on the right side:
Example Copy
Tooltip Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-placement=»».
Name | Type | Default | Description | Try it |
---|---|---|---|---|
animation | boolean | true |
Specifies whether to add a CSS fade transition effect when showing and hiding the tooltip
|
Try it |
container | string, or the boolean false | false | Appends the tooltip to a specific element. Example: container: ‘body’ | Try it |
delay | number, or object | Specifies the number of milliseconds it will take to show and hide the tooltip.To specify a delay for showing and another one for hiding, use the object structure:delay: {show: 500, hide: 100} — which will take 500 ms to show the tooltip, but only 100 ms to hide it | Try it | |
html | boolean | false | Specifies whether to accept HTML tags in the tooltip:
|
Try it |
placement | string | «top» | Specifies the tooltip position. Possible values:
|
Try it |
selector | string, or the boolean false | false | Adds the tooltip to a specified selector | Try it |
template | string | Base HTML to use when creating the tooltip. The tooltip’s title will be inserted into the element having the class .tooltip-inner and the element with the class .tooltip-arrow will become the tooltip’s arrow.The outermost wrapper element should have the .tooltip class. | ||
title | string | «» | Specifies the text that should be displayed inside the tooltip | Try it |
trigger | string | «hover focus» | Specifies how the tooltip is triggered. Possible values:
|
Try it |
offset | number or a string | Offset of the tooltip relative to its target | ||
fallbackPlacement | string or an aray | «flip» | Specifies which position Popper wil use on fallback | |
boundary | string or element | «scrollParent» | Overflow constraint boundary of the tooltip. Accepts the values «viewport», «window» or «scrollParent», or an HTML element |
С этим читают