问题
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