Подтвердить что ты не робот

JQuery - Twitter Bootstrap - закрыть все popovers на теле любые элементы фокуса

Я пытаюсь закрыть любой popover открывается, когда any body element (а не сам popover) is focused,

поэтому я делаю:

 $(document.body).on('focus focusout focusin', function(e) {
  if( e.target.classList.contains('popover') ){return false;}
  else{
    $('*').popover('hide');
  }
  // code to close the popover
});

это отлично работает на Chrome, но не на FF, на FF мне нужно focusin and focusout до закрытия popover.

вот мой пример, работающий только для хрома: http://jsfiddle.net/CU5U5/4/

Как я могу это исправить?

4b9b3361

Ответ 1

Альтернатива:

$(document).on('focus', ':not(.popover)', function(){
    $('.popover').popover('hide');
});

Edit:

Итак, мой вышеприведенный ответ неверен. Вам нужно вызвать .popover('hide') в элементе, который был создан popover... не сам .popover. И вам нужно прекратить распространение события клика по ссылке (т.е. Вернуть значение false в обработчике кликов), чтобы он не дошел до корня документа. См. Это для ответа http://jsfiddle.net/aFacG/1/.

HTML

<a data-content="a popover" id="mypopover" href="#">click me</a>

JS

$(document).ready(function(){
  $("#mypopover").popover();

  $(document).on('click', function(){
      $("#mypopover").popover('hide');
  });

  $('#mypopover').click(function(){
      return false;
  });
});

Ответ 2

Проблема с текущим принятым ответом заключается в том, что popover скрывается, даже если вы нажимаете внутри всплывающей подсказки (плохо, если у вас есть элемент, с которым вы хотите взаимодействовать внутри popover..like поля ввода).

Используйте метод stopPropagation в контейнере popover, чтобы предотвратить событие скрыть от DOM.

UPDATE (исходный url-адрес изменен): http://jsfiddle.net/bNvX7/10/

$(document).ready(function(){

    //Initialize popover on element
    $("#mypopover").popover();

    //Attach click handler to document
    $(document).bind('click', function (e) {
        $("#mypopover").popover('hide');
    });

    //Dont hide when I click anything inside #container
    $('#container').bind('click', function(e) {
        e.stopPropagation();
    });
});

Ответ 3

Быть очень упрощенным:

$('.popover').remove();

Ответ 4

Вот несколько более общий подход, который требует только одного обработчика и работает для всех popovers, где toggle/link содержит атрибут data-rel= "popover", например:

HTML

<a href="#" data-rel="popover">toggle</a>

JS

  $(document).on('click', function(event) {
    var $clicked = $(event.target);

    if ($clicked.closest('[data-rel="popover"]').length) {
      return;
    } else if ($clicked.closest('.popover').length) {
      event.stopPropagation();
    } else {
      $('[data-rel="popover"]').popover('hide');
    }
  });

Ответ 5

Возможно, вы могли бы попробовать следующее:

        // Part 1: initialize the popver
        var button = template.find(".itemInfo button");
        // add a class name to identify the target later.
        button.addClass("popover-toggle");

        var content = $("<div>test</div>");

        button.popover({
            container:"body",
            content: content,
            html:true,
            placement:"top",
            title:"Popover title",
            trigger:'click'
        });

        // Part 2: add click event listener 
        $(document).on("click", function(event){
            var target = $(event.target);
            $.each( $(".popover-toggle"), function(index, value){
                var _target = $(value);
                // not click on the button and not click on the popover it self
                if( !target.is( _target ) && target.closest(".popover").length == 0 ){
                    _target.popover("hide");
                }
            });
        });

Не лучшая практика, но она отлично работает как на Chrome, так и на FF.

Ответ 6

Вызов

$('.popover').popover('hide');

закроет все открытые в данный момент всплывающие окна.