【问题标题】:Bootstrap popover hide on outside click. Opens only on second clickBootstrap 弹出窗口隐藏在外部点击。仅在第二次单击时打开
【发布时间】:2015-12-29 21:25:58
【问题描述】:

使用其他答案中的解决方案在外部点击时隐藏 Bootstrap 弹出窗口。

但是,它需要单击两次才能再次打开弹出框(如果我通过单击外部将其关闭)。

它工作正常,当我使用按钮关闭它时,它会在第一次单击时打开。

这是重新创建的问题:http://codepen.io/olegovk/pen/BjQmQe

使用的html:

<!-- Popup button -->
<a id="menu-button" class="menu-button" data-html="true" role="button" data-container="body" data-toggle="popover" data-placement="bottom">Menu</a>

<!-- Popup content -->
<div id="menu-content">
  <h1>Hello</h1>
  <p>Good bye</p>
  <a href="#">Link</a>
</div>

还有 jQuery:

$('#menu-button').popover({
  content: $('#menu-content').html(),
  html: true
});
$('html').on('click', function(e) {
  if (typeof $(e.target).data('original-title') == 'undefined' &&
    !$(e.target).parents().is('.popover.in')) {
    $('[data-original-title]').popover('hide');
  }
});

任何想法为什么会发生以及如何使弹出窗口始终在第一次点击时打开?

注意:我发现无法使用这种“官方”解决方案,因为它无法点击弹出窗口中的链接:http://getbootstrap.com/javascript/#dismiss-on-next-click

【问题讨论】:

    标签: javascript jquery html css twitter-bootstrap


    【解决方案1】:

    您不需要额外的 Js 来关闭弹出框,正如文档中所说的 docs

    下次点击关闭

    使用焦点触发器在用户下次单击时关闭弹出框。

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

    data-trigger="focus" 在用户下次点击时关闭弹出框。

    【讨论】:

    • 谢谢你,但是我的弹出窗口中有菜单链接,这种技术使得无法点击它们。不幸的是,简单的溃败并没有奏效。
    【解决方案2】:

    在许多情况下(主要是文档中的其余代码),一旦您离开弹出框,您就必须重新关注它。该事件不容易将点击事件绑定到 html 或正文。按钮比超链接更容易重新获得焦点。 (这是我的理论,我会质疑它,但这是我在这里和那里读到的)关键是,这段代码有效,哈哈,这很重要,不是吗?

    如果需要,我建议您将超链接更改为按钮并设置样式以使其看起来像超链接,并使用此处提供的 jFiddle 中的代码

    $('[data-toggle="popover"]').popover();
    
    
    
    
    $('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');
        }
    });
    });
    

    这里正在工作jfiddle

    【讨论】:

    • 谢谢,但 jfiddle 示例似乎不起作用?不关闭外部点击?
    • 听从了您的建议并用按钮替换了链接:codepen.io/olegovk/pen/yeVjMp 但仍然无法正常工作
    • 我明白了,单击同一行上的按钮外部(按钮旁边)。它会起作用的。请记住,jfiddle 在查看器中提供带有 html 文档的 iframe。如果您在 iframe 外部单击,从技术上讲,您并没有转义按钮。
    • 右键单击该按钮并使用 Web 开发工具对其进行检查。你会看到那个 iframe。
    • 那里!我将 html 和 body 的高度设置为 100%,以便您可以单击文档上的任何位置。确保您的文档(网站)有 html,body{height:100%}
    猜你喜欢
    • 2015-08-11
    • 2013-12-26
    • 2022-12-31
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    相关资源
    最近更新 更多