如何通过单击页面上的任何位置(其他)来关闭 Twitter Bootstrap 弹出窗口? [英] How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?
问题描述
我目前在 Twitter Bootstrap 中使用弹出框,如下所示:
I'm currently using popovers with Twitter Bootstrap, initiated like this:
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).click(function(e) {
$(this).popover('toggle');
e.preventDefault();
});
如您所见,它们是手动触发的,单击 .popup-marker(带有背景图像的 div)会切换弹出框.这很好用,但我还希望能够通过点击页面上的任何其他地方(但不是在弹出框本身上!)来关闭弹出框.
As you can see, they're triggered manually, and clicking on .popup-marker (which is a div with a background image) toggles a popover. This works great, but I'd like to also be able to close the popover with a click anywhere else on the page (but not on the popover itself!).
我尝试了一些不同的方法,包括以下内容,但没有显示结果:
I've tried a few different things, including the following, but with no results to show for it:
$('body').click(function(e) {
$('.popup-marker').popover('hide');
});
如何通过单击页面上的任何其他位置而不是单击弹出框本身来关闭弹出框?
推荐答案
假设在任何时候只有一个 popover 可见,您可以使用一组标志来标记何时有一个 popover 可见,然后才隐藏它们.
Presuming that only one popover can be visible at any time, you can use a set of flags to mark when there's a popover visible, and only then hide them.
如果你在文档正文上设置了事件监听器,它会在你点击标有'popup-marker'的元素时触发.所以你必须在事件对象上调用 stopPropagation()
.并在单击弹出窗口本身时应用相同的技巧.
If you set the event listener on the document body, it will trigger when you click the element marked with 'popup-marker'. So you'll have to call stopPropagation()
on the event object. And apply the same trick when clicking on the popover itself.
以下是执行此操作的有效 JavaScript 代码.它使用 jQuery >= 1.7
Below is a working JavaScript code that does this. It uses jQuery >= 1.7
jQuery(function() {
var isVisible = false;
var hideAllPopovers = function() {
$('.popup-marker').each(function() {
$(this).popover('hide');
});
};
$('.popup-marker').popover({
html: true,
trigger: 'manual'
}).on('click', function(e) {
// if any other popovers are visible, hide them
if(isVisible) {
hideAllPopovers();
}
$(this).popover('show');
// handle clicking on the popover itself
$('.popover').off('click').on('click', function(e) {
e.stopPropagation(); // prevent event for bubbling up => will not get caught with document.onclick
});
isVisible = true;
e.stopPropagation();
});
$(document).on('click', function(e) {
hideAllPopovers();
isVisible = false;
});
});
http://jsfiddle.net/AFffL/539/
唯一的警告是您将无法同时打开 2 个弹出框.但我认为这会让用户感到困惑,无论如何:-)
The only caveat is that you won't be able to open 2 popovers at the same time. But I think that would be confusing for the user, anyway :-)
这篇关于如何通过单击页面上的任何位置(其他)来关闭 Twitter Bootstrap 弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!