Twitter Bootstrap: скрыть другие popovers, когда кто-то открыт
Следующий код Bootstrap дает мне "липкий" popover (так что пользователи могут взаимодействовать с содержимым внутри popover). Проблема в том, что при открытии popover другие popovers должны быть закрыты (скрыты). Любая идея, как я могу это реализовать?
$("[rel=popover]").popover({placement:'bottom', trigger:'manual'}).hover(function(){
$(this).popover('show');
e.preventDefault();
});
Ответы
Ответ 1
У меня была игра с этим, и есть еще несколько проблем, связанных с запуском ручного шоу/скрыть, чтобы это было хорошо. Наведение на самом деле mousein
и mouseout
, и если вы не добавите некоторые дополнительные проверки, вы столкнетесь с проблемами, которые я только что сделал!
Вот мое решение в действии, и я попытаюсь объяснить, что я сделал.
$(function () {
var overPopup = false;
$('[rel=popover]').popover({
trigger: 'manual',
placement: 'bottom'
// replacing hover with mouseover and mouseout
}).mouseover(function (e) {
// when hovering over an element which has a popover, hide
// them all except the current one being hovered upon
$('[rel=popover]').not('#' + $(this).attr('id')).popover('hide');
var $popover = $(this);
$popover.popover('show');
// set a flag when you move from button to popover
// dirty but only way I could think of to prevent
// closing the popover when you are navigate across
// the white space between the two
$popover.data('popover').tip().mouseenter(function () {
overPopup = true;
}).mouseleave(function () {
overPopup = false;
$popover.popover('hide');
});
}).mouseout(function (e) {
// on mouse out of button, close the related popover
// in 200 milliseconds if you're not hovering over the popover
var $popover = $(this);
setTimeout(function () {
if (!overPopup) {
$popover.popover('hide');
}
}, 200);
});
});
Это отлично сработало для меня со следующим html:
<a href="#" id="example1" class="btn large primary" rel="popover" data-content="Example 1!!!" data-original-title="Example 1 title">Button 1</a>
<a href="#" id="example2" class="btn large primary" rel="popover" data-content="Example 2!!!" data-original-title="Example 2 title">Button 2</a>
<a href="#" id="example3" class="btn large primary" rel="popover" data-content="Example 3!!!" data-original-title="Example 3 title">Button 3</a>
Надеюсь, что тебя выберет:)
Ответ 2
Здесь очень простое решение (не мое решение, но прекрасно работает):
$('.link-popover').click(function(){
$('.link-popover').not(this).popover('hide'); //all but this
});
Ответ 3
В соответствии с документами bootstrap: Используйте триггер фокуса, чтобы отклонять popovers при следующем щелчке, который пользователь делает.
<a href="#" tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data- trigger="focus" title="Dismissible popover" data-content="And here some amazing content. It very engaging. Right?">Dismissible popover</a>
Ответ 4
Используя Обратные вызовы Bootstrap 3, вы можете сделать:
$(document).on('show.bs.popover', function() {
$('.popover').not(this).popover('hide');
});
и в coffeescript
$(document).on 'show.bs.popover', ->
$('.popover').not(this).popover('hide')
Ответ 5
Решение Simpiet для закрытия всех остальных popovers. Это можно добавить к любому событию, в котором будет отображаться всплывающее окно, например, щелчок/наведение и т.д. Перед тем, как вы увидите палочку popover в следующем коде:
$('.popover').not(this).hide(); //Hides all other popovers
Это приведет к удалению всех popovers на странице, кроме текущего
Ответ 6
$('li').popover({
title: 'My title',
content: 'My content'
})
.on('show.bs.popover', function() {
if (window._bsPopover) {
$(window._bsPopover).popover('hide')
}
window._bsPopover= this;
})
.on('hide.bs.popover', function() {
window._bsPopover= null; // see Peter Jacoby comment
});
Ответ 7
Я использовал функцию для своего контента, поэтому у меня (в coffeescript):
provideContentForPopover = (element) ->
$('.some-selector').not(element).popover 'hide'
"some content to be returned"
$('.some-selector').popover
content: -> provideContentForPopover @
Ответ 8
$('.allThePopovers').click(function () {
if ($(this).hasClass('popoverIsOpen')) {
$(this).removeClass('popoverIsOpen');
} else {
$('.popoverIsOpen').popover('hide');
$('.allThePopovers').removeClass('popoverIsOpen');
$(this).addClass('popoverIsOpen');
});
Просто замените клик мышью или мышью в соответствии с вашими потребностями.
Ответ 9
Это отлично работает, если вы хотите открыть только один popover, открыв и закрыв щелчком (позиция курсора не имеет значения):
$('[data-toggle="popover"]').popover({ html: true }).bind("click", function(){
if(!$(this).parent().children("a").first().is(":hover"))
$( '[data-toggle="popover"]').popover("hide");
else
$( '[data-toggle="popover"]').not($(this).parent().children("a").first()).popover("hide");
return false;
});
Важно, чтобы каждый popover имел отдельного родителя, например
<ul> <li> <popover> </li> <li> <popover> </li> </ul>
HTML:
<li>
<a id="quickmenu-i-305" data-toggle="popover" data-placement="bottom" data-title="Title" data-content='<h2>Plesk Login</h2>' href="Plesk Login">Ihr Kundenbereich</a>
</li>
Ответ 10
Я смог выполнить подобный подход, просто скрыв, какой бы ни был popover, который не был нажат. Я не уверен, но, похоже, для меня это хорошо. Это означает, что popover отображается на клике и остается живым. Он скрыт, когда нажимается другая кнопка.
<script>
$(function () {
$('[rel=popover]').popover({
}).click(function (e) {
$('[rel=popover]').not('#friend_' + $(this).attr('id')).popover('hide');
});
});
</script>
Ответ 11
более простой способ выполнения задания:
$('[rel=popover]').popover({
trigger: 'manual',
placement: 'bottom'
}).click(function(e) {
$('[rel=popover]').not('#' + $(this).attr('id')).popover('hide');
var $popover = $(this);
$popover.popover('toggle');
});
просто убедитесь, что ваш popover имеет уникальный идентификатор;]
ваш popover будет вести себя так же, как и по умолчанию, сразу один popover.
Ответ 12
я обнаружил, что есть некоторые проблемы с динамическими popovers, поэтому
вот 2 решения для статических и динамических popovers:
Первое решение - использовать опцию popover triger:'focus'
но этот вариант не будет работать на некоторых устройствах Android.
а второй:
$('body').popover({
html: true,
//this is for static and dynamic popovers
selector: '[data-toggle="popover"]',
trigger: 'click',
content: function () {
//i am using predefined content for popovers. replace with your code or remove at all
return $($(this).data('templateselector') + ' .content').html();
},
title: function () {
return $($(this).data('templateselector') + ' .title').html();
},
container: 'body'
}).on('show.bs.popover', function (e) {
// i've found that showed popovers has aria-describedby
// and $('[data-toggle="popover"]).not(this) not working for dynamic popovers so i came with this:
$('[data-toggle="popover"][aria-describedby]').popover('hide');
var trigger = $(e.target);
// this is for adding custom class for popover container
// just remove it if you dont need
trigger.data('bs.popover').tip().addClass($(trigger).data('class'));
});
Ответ 13
Используйте этот метод, чтобы скрыть все другие popover, когда вы наводите курсор мыши или нажимаете на другой элемент, чтобы открыть его.
один
два
три
четыре
$(document).ready(function(){
$('.btnPopover').mouseover(function(){
$(this).popover({
html: true,
trigger: 'manual'
}).popover('show');
$('.btnPopover').not(this).popover('hide');
});
});
Убедитесь, что вы загрузили загрузочную страницу bootstrap.js и bootstrap.css.
Надеюсь, это поможет.
Ура!!
Сурай Кумар
Ответ 14
Для совместимости должен использоваться тег привязки <a>
.
Моя скрипта: https://jsfiddle.net/oneflame/pnb8Ltj3/
Bootstrap Ссылка - http://getbootstrap.com/javascript/#dismiss-on-next-click p >
<div id="FragmentText1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, est laborum.
</div>
$(document).ready(function(){
$('a.LexicalEntry').popover({
html : true,
content: function() {
return getLexicalDefinition($(this).text());
} ,
trigger: 'focus',
placement: 'auto',
html: true,
container: 'body'
});
});
// *** Injects HTML into raw text.
// *** Splits the content string using a whitespace regular expression.
$('#FragmentText1').each(function() {
// var words = $.trim( $(this).text() ).split(/\s+/g);
var $this = $(this);
$this.html(
$this.text().trim().replace(/\b(\w+)\b/g,
"<a tabindex='0' class='LexicalEntry'' role='button' title='Definition: $1'>$1</a>"
));
});