在外部单击时使用 HTML 关闭弹出窗口

Close popover with HTML on click outside

我正在使用 Bootstrap 弹出框,弹出框内容是 HTML。我正在使用下面的代码来初始化弹出窗口。此代码基于 这个答案。 弹出框内容位于 div 中,id 为 #song-status-popover

$(".song-status-link").popover({
            html: true,
            placement: 'bottom',
            content: function () {
                return $("#song-status-popover").html();
            }
});

我想在弹出窗口外单击时关闭弹出窗口,因此我使用了以下代码:

$('html').on('mouseup', function (e) {
            if (!$(e.target).closest('.popover').length) {
                $('.popover').each(function () {
                    $(this).closest('div.popover').popover('hide');
                });
            }
});

到目前为止一切正常,但同时使用这两种代码时我遇到了一个问题。当我打开弹出窗口并在外部单击以将其关闭时,如果我再次单击 link 以打开弹出窗口,它不会在第一次单击时打开。我必须点击两次才能打开它。

我想知道我遗漏了什么以及为什么我在点击外面关闭弹出窗口后无法一键打开。请帮忙!

更新: 我相信当我在外面点击时它会隐藏弹出窗口,但 bootstrap 仍然认为它是打开的并且在第一次点击时它实际上认为它是关闭的并且第二次单击它会打开弹出窗口。

您必须 .find() 通过检查 DOM 中的 visiblility/availablity 和 :visibile:

if ($(this).find('.popover:visible').length) {
    $('.popover').popover('hide');
}

试试下面的代码

$('html').on('click', function(e) {
  if (!$(e.target).is('.song-status-link') && $(e.target).closest('.popover').length == 0) {
    $(".song-status-link").popover('hide');
  }
});

http://jsfiddle.net/xzeb91hf/

bootstrap 这实际上是可能的,唯一的缺点是弹出框内不能有任何可聚焦的元素。

official documentation 中查找 下次点击时关闭 部分。

是根据focus事件触发popover,blur事件再次隐藏。在触发 link 之外单击将触发模糊事件并且弹出窗口将隐藏。