点击外部区域来关闭Bootstrap弹出窗口

3
如何通过点击弹出框外部来关闭Bootstrap弹出框。目前只有开关链接可以打开它。
HTML
 <div class="widget-rating">
          <span class="rateit rating-average"></span>
          <a class="btn btn-mini" href="javascript:void(0)"><b class="caret"></b></a>
 </div>

以下是JavaScript代码:

element.popoverAnchor.popover({
        title: "Rating",
        animation: false,
        html: true,
        content: "Loading...",
        placement: "bottom",
        trigger: "click"
      });
2个回答

6
$('body').on('click', function (e) {
    $('.popover-link').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');
        }
    });
});

参考资料: http://mattlockyer.com/2013/04/08/close-a-twitter-bootstrap-popover-when-clicking-outside/

本文介绍了如何在单击 Twitter Bootstrap 弹出框外部时关闭弹出框。为此,我们需要使用 jQuery 监听事件,并检查触发事件的目标是否是弹出框以外的元素。如果是,则关闭弹出框。


根据我的HTML代码,你的js代码需要修改吗? - Sowmya
是的,您需要更改弹出元素的ID。看一下这个例子:http://jsfiddle.net/mattdlockyer/ZZXEj/7/。生活会变得非常简单。 - Vaibs_Cool

0
$('body').on('click', function (e) { 
    $("div.popover").each(function() {
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            $(this).prevAll('*:first').popover('hide');
        }
    }); 
});

通用修改适用于任何情况...无需为触发元素指定类


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接