简体   繁体   English

用户在弹出窗口外单击时关闭Bootstrap Popover

[英]Closing Bootstrap Popover When User Clicks Outside Popover

I have some content that's dynamically loaded on a webpage that contains popovers. 我有一些内容在包含弹出窗口的网页上​​动态加载。 For this reason I have to bind them to the body so they load and appear correctly. 出于这个原因,我必须将它们绑定到身体,以便它们加载并正确显示。

I'd like to find a way to hide the popovers when a user clicks outside the popover or on another popover trigger. 当用户点击弹出窗口或其他弹出窗口触发器时,我想找到隐藏弹出窗口的方法。

I found that if I "hide" the popover, the popover does indeed hide but the elements remain in the DOM. 我发现如果我“隐藏”popover,popover确实隐藏了但元素仍保留在DOM中。 This means that active links in the popover remain "clickable". 这意味着popover中的活动链接仍然是“可点击的”。

If I instead destroy the popover, it hides, but is unable to re-activate if clicked on. 如果我改为破坏弹出窗口,它会隐藏,但如果单击则无法重新激活。 The only reliable way to hide the popover is to use "toggle". 隐藏弹出窗口的唯一可靠方法是使用“切换”。 This increases the complexity of determining which popovers to hide. 这增加了确定隐藏哪些弹出窗口的复杂性。

Please see this JSFiddle with all this code. 请使用所有这些代码查看此JSFiddle

HTML HTML

<a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.yahoo.com'>http://www.yahoo.com</a>" class="some-popover-link">Yahoo</a>
<br><br> <br> <br> <br>  <a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.google.com'>http://www.google.com</a>" class="some-popover-link">Google</a>
<br><br> <br> <br> <br>  <a href="#" data-toggle="popover" data-original-title="" data-content="<a href='http://www.microsoft.com'>http://www.microsoft.com</a>" class="some-popover-link">Microsoft</a>

JavaScript JavaScript的

$('.some-popover-link').popover({
    container: 'body',
    html: true,
    placement: 'bottom'
});

$(document).click(function (e) {
    $('.some-popover-link').each(function () {
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide'); // this hides popover, but content remains
            return;
        }
    });
});

This relies on internal implementation so be careful but it should work. 这依赖于内部实现,所以要小心,但它应该工作。 JSFiddle Link JSFiddle链接

if ($(this).data('bs.popover').tip().hasClass('in')) {
    $(this).popover('toggle');
}

Use this code: 使用此代码:

$(document).mouseup(function (e) {
    if ($('.popover').has(e.target).length === 0) {
        $('.popover').toggleClass('in').remove();
        return;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM