Hide Bootstrap Popover when clicked outside of the popover

我的未来我决定 提交于 2021-01-29 10:47:03

问题


I have the following setup for a bootstrap popover. The popover appears when the page is loaded and if I click on the popover, it disappears. What I would really like though is for it to disappear if I click outside the popover or even better on the next click. Any ideas on how to make this work?

$('div').on('hide.bs.popover', function (e) {
        e.preventDefault();
    });

    $(document).ready(function() {
        $("div").popover("show");
    });



    $('body').on('click', '.popover', function () {
        $(this).hide();
    });
<div class="dropdown pull-right" data-toggle="popover" data-placement="left" data-content="Main menu" style="right: -2px; top: 3px;">

<a href="#" class="glyphicon glyphicon-th dropdown-toggle" data-toggle="dropdown" style="color: #317EAC; text-decoration: none !important; font-size: 22px;"></a>
</div>

回答1:


As per documentation: Use the focus trigger to dismiss popovers on the next click that the user makes. So use data-trigger="focus"

Specific markup required for dismiss-on-next-click For proper cross-browser and cross-platform behavior, you must use the tag, not the tag, and you also must include the role="button" and tabindex attributes.

<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?">Dismissible popover</a>




回答2:


$('body').on('click', function (e) {
    $('[data-toggle=popover]').each(function () {
        // hide any open popovers when the anywhere else in the body is clicked
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).popover('hide');
        }
    });
});



回答3:


Found the solution for this:

$(document).ready(function() {
    $("div").popover("show");
});

$('body').on('click', function (e) {
    if ($(e.target).data('toggle') !== 'popover'
        && $(e.target).parents('.popover.in').length === 0) {
        $('[data-toggle="popover"]').popover('hide');
    }
});


来源:https://stackoverflow.com/questions/52128159/hide-bootstrap-popover-when-clicked-outside-of-the-popover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!