我们能否让弹窗以与模式相同的方式被关闭,即。当用户点击它们之外的某个地方时让它们关闭?
不幸的是,我不能只使用真正的模式而不是弹出窗口,因为模式意味着 position:fixed 并且那将不再是弹出窗口。 :(
最佳答案
更新:一个稍微更稳健的解决方案:http://jsfiddle.net/mattdlockyer/C5GBU/72/
对于仅包含文本的按钮:
$('body').on('click', function (e) {
//did not click a popover toggle or popover
if ($(e.target).data('toggle') !== 'popover'
&& $(e.target).parents('.popover.in').length === 0) {
$('[data-toggle="popover"]').popover('hide');
}
});
对于包含图标的按钮,请使用(此代码在 Bootstrap 3.3.6 中存在错误,请参阅此答案中的以下修复)
$('body').on('click', function (e) {
//did not click a popover toggle, or icon in popover toggle, or popover
if ($(e.target).data('toggle') !== 'popover'
&& $(e.target).parents('[data-toggle="popover"]').length === 0
&& $(e.target).parents('.popover.in').length === 0) {
$('[data-toggle="popover"]').popover('hide');
}
});
对于 JS 生成的 Popovers 使用 '[data-original-title]'
代替 '[data-toggle="popover"]'
警告:上述解决方案允许同时打开多个弹出窗口。
请一次弹出一个:
更新: Bootstrap 3.0.x,查看代码或fiddle http://jsfiddle.net/mattdlockyer/C5GBU/2/
$('body').on('click', function (e) {
$('[data-toggle="popover"]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
});
这会处理关闭已打开但未被点击或它们的链接尚未被点击的弹出窗口。
更新: Bootstrap 3.3.6,see fiddle
修复了关闭后需要点击 2 次才能重新打开的问题
$(document).on('click', function (e) {
$('[data-toggle="popover"],[data-original-title]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
(($(this).popover('hide').data('bs.popover')||{}).inState||{}).click = false // fix for BS 3.3.6
}
});
});
更新:利用之前改进的条件,实现了这个解决方案。修复双击和ghost popover问题:
$(document).on("shown.bs.popover",'[data-toggle="popover"]', function(){
$(this).attr('someattr','1');
});
$(document).on("hidden.bs.popover",'[data-toggle="popover"]', function(){
$(this).attr('someattr','0');
});
$(document).on('click', function (e) {
$('[data-toggle="popover"],[data-original-title]').each(function () {
//the 'is' for buttons that trigger popups
//the 'has' for icons within a button that triggers a popup
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
if($(this).attr('someattr')=="1"){
$(this).popover("toggle");
}
}
});
});
关于twitter-bootstrap - 如何通过单击外部来关闭 Twitter Bootstrap 弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45670874/