简体   繁体   English

如何通过从页面上的任何地方(其他地方)单击来关闭 Twitter Bootstrap 弹出窗口?

[英]How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

I'm currently using popovers with Twitter Bootstrap, initiated like this:我目前正在使用带有 Twitter Bootstrap 的弹出框,如下所示:

$('.popup-marker').popover({
        html: true,
        trigger: 'manual'
    }).click(function(e) {
        $(this).popover('toggle');
        e.preventDefault();
    });

As you can see, they're triggered manually, and clicking on .popup-marker (which is a div with a background image) toggles a popover.如您所见,它们是手动触发的,单击 .popup-marker(带有背景图像的 div)会切换弹出框。 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');
});

How can I close the popover with a click anywhere else on the page, but not with a click onthe popover itself?如何通过单击页面上的其他任何位置而不是单击弹出框本身来关闭弹出框?

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.假设在任何时候只有一个弹出窗口可见,您可以使用一组标志来标记何时有一个弹出窗口可见,然后才隐藏它们。

If you set the event listener on the document body, it will trigger when you click the element marked with 'popup-marker'.如果你在文档正文上设置了事件监听器,它会在你点击标有'popup-marker'的元素时触发。 So you'll have to call stopPropagation() on the event object.所以你必须在事件对象上调用stopPropagation() And apply the same trick when clicking on the popover itself.并在单击弹出窗口本身时应用相同的技巧。

Below is a working JavaScript code that does this.下面是执行此操作的有效 JavaScript 代码。 It uses jQuery >= 1.7它使用 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/ http://jsfiddle.net/AFffL/539/

The only caveat is that you won't be able to open 2 popovers at the same time.唯一需要注意的是,您将无法同时打开 2 个弹出窗口。 But I think that would be confusing for the user, anyway :-)但我认为这会让用户感到困惑,无论如何:-)

This is even easier :这更容易:

$('html').click(function(e) {
    $('.popup-marker').popover('hide');
});

$('.popup-marker').popover({
    html: true,
    trigger: 'manual'
}).click(function(e) {
    $(this).popover('toggle');
    e.stopPropagation();
});

I had a similar need, and found thisgreat little extension of the Twitter Bootstrap Popover by Lee Carmichael, called BootstrapX - clickover .我有类似的需求,并发现了 Lee Carmichael 的 Twitter Bootstrap Popover 的这个很棒的小扩展,称为 BootstrapX - clickover He also has some usage exampleshere .在这里也有一些使用示例。 Basically it will change the popover into an interactive component which will close when you click elsewhere on the page, or on a close button within the popover.基本上它会将弹出窗口更改为一个交互式组件,当您单击页面上的其他地方或弹出窗口中的关闭按钮时,该组件将关闭。 This will also allow multiple popovers open at once and a bunch of other nice features.这也将允许同时打开多个弹出窗口和一堆其他不错的功能。

Plugin can be found here .插件可以在这里找到

Usage example使用示例

<button rel="clickover" data-content="Show something here. 
    <button data-dismiss='clickover'
    >Close Clickover</button>"
>Show clickover</button>

javascript: javascript:

// load click overs using 'rel' attribute
$('[rel="clickover"]').clickover();

The accepted solution gave me some issues (clicking on the '.popup-marker' element of the opened popover made the popovers not work afterwards).接受的解决方案给了我一些问题(单击打开的弹出窗口的“.popup-marker”元素后弹出窗口不起作用)。 I came up with this other solution that works perfectly for me and it's quite simple (I'm using Bootstrap 2.3.1):我想出了另一个非常适合我的解决方案,它非常简单(我使用的是 Bootstrap 2.3.1):

$('.popup-marker').popover({
    html: true,
    trigger: 'manual'
}).click(function(e) {
    $('.popup-marker').not(this).popover('hide');
    $(this).popover('toggle');
});
$(document).click(function(e) {
    if (!$(e.target).is('.popup-marker, .popover-title, .popover-content')) {
        $('.popup-marker').popover('hide');
    }
});

UPDATE: This code works with Bootstrap 3 as well!更新:此代码也适用于 Bootstrap 3!

read "Dismiss on next click" here http://getbootstrap.com/javascript/#popovers在这里阅读“在下次点击时关闭” http://getbootstrap.com/javascript/#popovers

You can use the focus trigger to dismiss popovers on the next click, but you have to use use the <a> tag, not the <button> tag, and you also must include a tabindex attribute...您可以使用焦点触发器在下次单击时关闭弹出窗口,但您必须使用<a>标签,而不是<button>标签,并且您还必须包含tabindex属性...

Example:例子:

<a href="#" tabindex="0" class="btn btn-lg btn-danger"
  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>

All of the existing answers are fairly weak, as they rely on capturing all document events then finding active popovers, or modifying the call to .popover() .所有现有的答案都相当薄弱,因为它们依赖于捕获所有文档事件,然后找到活动的弹出框,或者修改对.popover()的调用。

A much better approach is to listen for show.bs.popover events on the document's body then react accordingly.更好的方法是侦听文档正文上的show.bs.popover事件,然后做出相应的反应。 Below is code which will close popovers when the document is clicked or esc is pressed, only binding event listeners when popovers are shown:以下是在单击文档或按下esc时关闭弹出窗口的代码,在显示弹出窗口时绑定事件侦听器:

function closePopoversOnDocumentEvents() {
  var visiblePopovers = [];

  var $body = $("body");

  function hideVisiblePopovers() {
    $.each(visiblePopovers, function() {
      $(this).popover("hide");
    });
  }

  function onBodyClick(event) {
    if (event.isDefaultPrevented())
      return;

    var $target = $(event.target);
    if ($target.data("bs.popover"))
      return;

    if ($target.parents(".popover").length)
      return;

    hideVisiblePopovers();
  }

  function onBodyKeyup(event) {
    if (event.isDefaultPrevented())
      return;

    if (event.keyCode != 27) // esc
      return;

    hideVisiblePopovers();
    event.preventDefault();
  }

  function onPopoverShow(event) {
    if (!visiblePopovers.length) {
      $body.on("click", onBodyClick);
      $body.on("keyup", onBodyKeyup);
    }
    visiblePopovers.push(event.target);
  }

  function onPopoverHide(event) {
    var target = event.target;
    var index = visiblePopovers.indexOf(target);
    if (index > -1) {
      visiblePopovers.splice(index, 1);
    }
    if (visiblePopovers.length == 0) {
      $body.off("click", onBodyClick);
      $body.off("keyup", onBodyKeyup);
    }
  }

  $body.on("show.bs.popover", onPopoverShow);
  $body.on("hide.bs.popover", onPopoverHide);
}

https://github.com/lecar-red/bootstrapx-clickover https://github.com/lecar-red/bootstrapx-clickover

It's an extension of twitter bootstrap popover and will solve the problem very simply.它是 twitter bootstrap popover 的扩展,可以非常简单地解决问题。

For some reason none of the other solutions here worked for me.出于某种原因,这里的其他解决方案都不适合我。 However, after a lot of troubleshooting, I finally arrived at this method which works perfectly (for me at least).然而,经过大量的故障排除后,我终于找到了这个完美的方法(至少对我来说)。

$('html').click(function(e) {
  if( !$(e.target).parents().hasClass('popover') ) {
    $('#popover_parent').popover('destroy');
  }
});

In my case I was adding a popover to a table and absolutely positioning it above/below the td that was clicked.就我而言,我正在向表格中添加一个弹出框,并将其绝对定位在点击的td上方/下方。 The table selection was handled by jQuery-UI Selectable so I'm not sure if that was interfering.表选择是由 jQuery-UI Selectable 处理的,所以我不确定这是否有干扰。 However whenever I clicked inside the popover my click handler which targeted $('.popover') never worked and the event handling was always delegated to the $(html) click handler.但是,每当我在弹出窗口中单击时,我针对$('.popover')单击处理程序就永远不会工作,并且事件处理始终委托给$(html)单击处理程序。 I'm fairly new to JS so perhaps I'm just missing something?我对 JS 还很陌生,所以也许我只是错过了一些东西?

Anyways I hope this helps someone!无论如何,我希望这对某人有所帮助!

I give all my popovers anchors the class activate_popover .我给我所有的弹出框锚点activate_popover类。 I activate them all at once onload我在加载时一次性激活它们

$('body').popover({selector: '.activate-popover', html : true, container: 'body'})

to get the click away functionality working I use (in coffee script):为了让我使用的点击功能正常工作(在咖啡脚本中):

$(document).on('click', (e) ->
  clickedOnActivate = ($(e.target).parents().hasClass("activate-popover") || $(e.target).hasClass("activate-popover"))
  clickedAway = !($(e.target).parents().hasClass("popover") || $(e.target).hasClass("popover"))
if clickedAway && !clickedOnActivate
  $(".popover.in").prev().popover('hide')
if clickedOnActivate 
  $(".popover.in").prev().each () ->
    if !$(this).is($(e.target).closest('.activate-popover'))
      $(this).popover('hide')
)

Which works perfectly fine with bootstrap 2.3.1与引导程序 2.3.1 完美配合

Even though there are a lot of solutions here, i'd like to propose mine as well, i don't know if there is some solution up there that solves it all, but i tried 3 of them and they had issues, like clicking on the popover it self makes it hide, others that if i had another popover buttons clicked both/multiple popovers would still appear (like in the selected solution), How ever, This one fixed it all即使这里有很多解决方案,我也想提出我的解决方案,我不知道那里是否有一些解决方案可以解决所有问题,但是我尝试了其中的 3 个,但它们遇到了问题,例如单击在弹出窗口上它自己隐藏,其他人如果我有另一个弹出窗口按钮点击两个/多个弹出窗口仍然会出现(就像在选定的解决方案中一样),但是,这个解决了所有问题

var curr_popover_btn = null;
// Hide popovers function
function hide_popovers(e)
{
    var container = $(".popover.in");
    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        if( curr_popover_btn != null )
        {
            $(curr_popover_btn).popover('hide');
            curr_popover_btn = null;
        }
        container.hide();
    }
}
// Hide popovers when out of focus
$('html').click(function(e) {
    hide_popovers(e);
});
$('.popover-marker').popover({
    trigger: 'manual'
}).click(function(e) {
    hide_popovers(e);
    var $popover_btns = $('.popover-marker');
    curr_popover_btn = this;
    var $other_popover_btns = jQuery.grep($($popover_btns), function(popover_btn){
                return ( popover_btn !== curr_popover_btn );
            });
    $($other_popover_btns).popover('hide');
    $(this).popover('toggle');
    e.stopPropagation();
});

I would set the focus to the newly created pop-over and remove it on blur.我会将焦点设置为新创建的弹出窗口并在模糊时将其删除。 That way it's not needed to check which element of the DOM has been clicked and the pop-over can be clicked, and selected too: it will not lose its focus and will not disappear.这样就不需要检查 DOM 的哪个元素被点击了,弹出框也可以被点击和选择:它不会失去焦点,也不会消失。

The code:代码:

    $('.popup-marker').popover({
       html: true,
       trigger: 'manual'
    }).click(function(e) {
       $(this).popover('toggle');
       // set the focus on the popover itself 
       jQuery(".popover").attr("tabindex",-1).focus();
       e.preventDefault();
    });

    // live event, will delete the popover by clicking any part of the page
    $('body').on('blur','.popover',function(){
       $('.popup-marker').popover('hide');
    });

Here is the solution which worked very fine for me, if it can help :这是对我来说非常有效的解决方案,如果它可以帮助的话:

/**
* Add the equals method to the jquery objects
*/
$.fn.equals = function(compareTo) {
  if (!compareTo || this.length !== compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

/**
 * Activate popover message for all concerned fields
 */
var popoverOpened = null;
$(function() { 
    $('span.btn').popover();
    $('span.btn').unbind("click");
    $('span.btn').bind("click", function(e) {
        e.stopPropagation();
        if($(this).equals(popoverOpened)) return;
        if(popoverOpened !== null) {
            popoverOpened.popover("hide");            
        }
        $(this).popover('show');
        popoverOpened = $(this);
        e.preventDefault();
    });

    $(document).click(function(e) {
        if(popoverOpened !== null) {
            popoverOpened.popover("hide");   
            popoverOpened = null;
        }        
    });
});

Here's my solution, for what it's worth:这是我的解决方案,它的价值:

// Listen for clicks or touches on the page
$("html").on("click.popover.data-api touchend.popover.data-api", function(e) {

  // Loop through each popover on the page
  $("[data-toggle=popover]").each(function() {

    // Hide this popover if it's visible and if the user clicked outside of it
    if ($(this).next('div.popover:visible').length && $(".popover").has(e.target).length === 0) {
      $(this).popover("hide");
    }

  });
});

I had some problem to get it working on bootstrap 2.3.2.我在引导程序 2.3.2 上运行时遇到了一些问题。 But i sloved it this way:但我是这样处理的:

$(function () {
  $(document).mouseup(function (e) {
        if(($('.popover').length > 0) && !$(e.target).hasClass('popInfo')) {
            $('.popover').each(function(){
                $(this).prev('.popInfo').popover('hide');
            });
        }
    });

    $('.popInfo').popover({
        trigger: 'click',
        html: true
    });
});

tweaked @David Wolever solution slightly:稍微调整了@David Wolever 解决方案:

function closePopoversOnDocumentEvents() {
  var visiblePopovers = [];

  var $body = $("body");

  function hideVisiblePopovers() {
    /* this was giving problems and had a bit of overhead
      $.each(visiblePopovers, function() {
        $(this).popover("hide");
      });
    */
    while (visiblePopovers.length !== 0) {
       $(visiblePopovers.pop()).popover("hide");
    }
  }

  function onBodyClick(event) {
    if (event.isDefaultPrevented())
      return;

    var $target = $(event.target);
    if ($target.data("bs.popover"))
      return;

    if ($target.parents(".popover").length)
      return;

    hideVisiblePopovers();
  }

  function onBodyKeyup(event) {
    if (event.isDefaultPrevented())
      return;

    if (event.keyCode != 27) // esc
      return;

    hideVisiblePopovers();
    event.preventDefault();
  }

  function onPopoverShow(event) {
    if (!visiblePopovers.length) {
      $body.on("click", onBodyClick);
      $body.on("keyup", onBodyKeyup);
    }
    visiblePopovers.push(event.target);
  }

  function onPopoverHide(event) {
    var target = event.target;
    var index = visiblePopovers.indexOf(target);
    if (index > -1) {
      visiblePopovers.splice(index, 1);
    }
    if (visiblePopovers.length == 0) {
      $body.off("click", onBodyClick);
      $body.off("keyup", onBodyKeyup);
    }
  }

  $body.on("show.bs.popover", onPopoverShow);
  $body.on("hide.bs.popover", onPopoverHide);
}

This question was also asked here and my answer provides not only a way to understand jQuery DOM traversal methods but 2 options for handling the closing of popovers by clicking outside.这里也有人问过这个问题,我的回答不仅提供了一种理解 jQuery DOM 遍历方法的方法,还提供了 2 个通过单击外部来处理弹出窗口关闭的选项。

Open multiple popovers at once or one popover at a time.一次打开多个弹出窗口或一次打开一个弹出窗口。

Plus these small code snippets can handle the closing of buttons containing icons!此外,这些小代码片段可以处理包含图标的按钮的关闭!

https://stackoverflow.com/a/14857326/1060487 https://stackoverflow.com/a/14857326/1060487

This one works like a charm and I use it.这个就像一个魅力,我使用它。

It will open the popover when you click and if you click again it will close, also if you click outside of the popover the popover will be closed.单击时它将打开弹出窗口,如果再次单击它将关闭,如果您在弹出窗口外单击,弹出窗口也将关闭。

This also works with more than 1 popover.这也适用于 1 个以上的弹出框。

    function hideAllPopovers(){
    $('[data-toggle="popover"]').each(function() {
        if ($(this).data("showing") == "true"){
            $(this).data("showing", "false");
            $(this).popover('hide');                
        }
    });
}
$('[data-toggle="popover"]').each(function() {
        $(this).popover({
            html: true,
            trigger: 'manual'
        }).click(function(e) {
            if ($(this).data("showing") !=  "true"){
                hideAllPopovers();
                $(this).data("showing", "true");
                $(this).popover('show');
            }else{
                hideAllPopovers();
            }
            e.stopPropagation();
        });
});

$(document).click(function(e) {
    hideAllPopovers();
});

Another solution, it covered the problem I had with clicking descendants of the popover:另一个解决方案,它涵盖了我在单击弹出窗口的后代时遇到的问题:

$(document).mouseup(function (e) {
    // The target is not popover or popover descendants
    if (!$(".popover").is(e.target) && 0 === $(".popover").has(e.target).length) {
        $("[data-toggle=popover]").popover('hide');
    }
});

I do it as below我这样做如下

$("a[rel=popover]").click(function(event){
    if(event.which == 1)
    {   
        $thisPopOver = $(this);
        $thisPopOver.popover('toggle');
        $thisPopOver.parent("li").click(function(event){
            event.stopPropagation();
            $("html").click(function(){
                $thisPopOver.popover('hide');
            });
        });
    }
});

Hope this helps!希望这可以帮助!

If you're trying to use twitter bootstrap popover with pjax, this worked for me:如果您尝试将 twitter bootstrap popover 与 pjax 一起使用,这对我有用:

App.Utils.Popover = {

  enableAll: function() {
    $('.pk-popover').popover(
      {
        trigger: 'click',
        html : true,
        container: 'body',
        placement: 'right',
      }
    );
  },

  bindDocumentClickEvent: function(documentObj) {
    $(documentObj).click(function(event) {
      if( !$(event.target).hasClass('pk-popover') ) {
        $('.pk-popover').popover('hide');
      }
    });
  }

};

$(document).on('ready pjax:end', function() {
  App.Utils.Popover.enableAll();
  App.Utils.Popover.bindDocumentClickEvent(this);
});

@RayOnAir, I have same issue with previous solutions. @RayOnAir,我对以前的解决方案有同样的问题。 I come close to @RayOnAir solution too.我也接近@RayOnAir 解决方案。 One thing that improved is close already opened popover when click on other popover marker.改进的一件事是当单击其他弹出框标记时关闭已打开的弹出框。 So my code is:所以我的代码是:

var clicked_popover_marker = null;
var popover_marker = '#pricing i';

$(popover_marker).popover({
  html: true,
  trigger: 'manual'
}).click(function (e) {
  clicked_popover_marker = this;

  $(popover_marker).not(clicked_popover_marker).popover('hide');
  $(clicked_popover_marker).popover('toggle');
});

$(document).click(function (e) {
  if (e.target != clicked_popover_marker) {
    $(popover_marker).popover('hide');
    clicked_popover_marker = null;
  }
});

I found this to be a modified solution of pbaron's suggestion above, because his solution activated the popover('hide') on all elements with class 'popup-marker'.我发现这是上面 pbaron 建议的修改解决方案,因为他的解决方案激活了所有具有“popup-marker”类的元素上的 popover('hide')。 However, when you're using popover() for html content instead of the data-content, as I'm doing below, any clicks inside that html popup actually activate the popover('hide'), which promptly closes the window.但是,当您将 popover() 用于 html 内容而不是数据内容时,正如我在下面所做的那样,该 html 弹出窗口内的任何点击实际上都会激活 popover('hide'),它会立即关闭窗口。 This method below iterates through each .popup-marker element and discovers first if the parent is related to the .popup-marker's id that was clicked, and if so then does not hide it.下面的这个方法遍历每个 .popup-marker 元素,首先发现父元素是否与被点击的 .popup-marker 的 id 相关,如果是,则不隐藏它。 All other divs are hidden...所有其他 div 都隐藏了...

        $(function(){
            $('html').click(function(e) {
                // this is my departure from pbaron's code above
                // $('.popup-marker').popover('hide');
                $('.popup-marker').each(function() {
                    if ($(e.target).parents().children('.popup-marker').attr('id')!=($(this).attr('id'))) {
                        $(this).popover('hide');
                    }
                });
            });

            $('.popup-marker').popover({
                html: true,
                // this is where I'm setting the html for content from a nearby hidden div with id="html-"+clicked_div_id
                content: function() { return $('#html-'+$(this).attr('id')).html(); },
                trigger: 'manual'
            }).click(function(e) {
                $(this).popover('toggle');
                e.stopPropagation();
            });
        });

I came up with this:我想出了这个:

My scenario included more popovers on the same page, and hiding them just made them invisible and because of that, clicking on items behind the popover was not possible.我的场景在同一页面上包含更多弹出窗口,隐藏它们只会使它们不可见,因此,无法单击弹出窗口后面的项目。 The idea is to mark the specific popover-link as 'active' and then you can simply 'toggle' the active popover.这个想法是将特定的弹出框链接标记为“活动”,然后您可以简单地“切换”活动弹出框。 Doing so will close the popover completely.这样做将完全关闭弹出窗口。

$('.popover-link').popover({ html : true, container: 'body' })

$('.popover-link').popover().on 'shown.bs.popover', ->
  $(this).addClass('toggled')

$('.popover-link').popover().on 'hidden.bs.popover', ->
  $(this).removeClass('toggled')

$("body").on "click", (e) ->
  $openedPopoverLink = $(".popover-link.toggled")
  if $openedPopoverLink.has(e.target).length == 0
    $openedPopoverLink.popover "toggle"
    $openedPopoverLink.removeClass "toggled"

I was trying to make a simple solution for a simple issue.我试图为一个简单的问题制定一个简单的解决方案。 Above posts are good but so complicated for a simple issue.上面的帖子很好,但对于一个简单的问题来说太复杂了。 So i made a simple thing.所以我做了一个简单的事情。 Just added a close button.刚刚添加了一个关闭按钮。 Its perfect for me.它对我来说是完美的。

            $(".popover-link").click(function(){
                $(".mypopover").hide();
                $(this).parent().find(".mypopover").show();
        })
        $('.close').click(function(){
    $(this).parents('.mypopover').css('display','none');
});



          <div class="popover-content">
        <i class="fa fa-times close"></i>
    <h3 class="popover-title">Title here</h3>
your other content here
        </div>


   .popover-content {
    position:relative;
    }
    .close {
        position:absolute;
        color:#CCC;
        right:5px;
        top:5px;
        cursor:pointer;
    }

I like this, simple yet effective..我喜欢这个,简单而有效..

var openPopup;

$('[data-toggle="popover"]').on('click',function(){
    if(openPopup){
        $(openPopup).popover('hide');

    }
    openPopup=this;
});

Add btn-popover class to your popover button/link that opens the popover.btn-popover类添加到打开弹出框的弹出框按钮/链接中。 This code will close the popovers when clicking outside of it.当点击它的外部时,此代码将关闭弹出窗口。

$('body').on('click', function(event) {
  if (!$(event.target).closest('.btn-popover, .popover').length) {
    $('.popover').popover('hide');
  }
});

An even easier solution, just iterate through all popovers and hide if not this .一个更简单的解决方案,只需遍历所有弹出窗口并隐藏如果不是this

$(document).on('click', '.popup-marker', function() {
    $(this).popover('toggle')
})

$(document).bind('click touchstart', function(e) {
    var target = $(e.target)[0];
    $('.popup-marker').each(function () {
        // hide any open popovers except for the one we've clicked
        if (!$(this).is(target)) {
            $(this).popover('hide');
        }
    });
});
$('.popForm').popover();

$('.conteneurPopForm').on("click",".fermePopover",function(){
    $(".popForm").trigger("click");
});

To be clear, just trigger the popover要清楚,只需触发弹出窗口

This should work in Bootstrap 4:这应该适用于 Bootstrap 4:

 $("#my-popover-trigger").popover({ template: '<div class="popover my-popover-content" role="tooltip"><div class="arrow"></div><div class="popover-body"></div></div>', trigger: "manual" }) $(document).click(function(e) { if ($(e.target).closest($("#my-popover-trigger")).length > 0) { $("#my-popover-trigger").popover("toggle") } else if (!$(e.target).closest($(".my-popover-content")).length > 0) { $("#my-popover-trigger").popover("hide") } })

Explanation:解释:

  • The first section inits the popover as per the docs: https://getbootstrap.com/docs/4.0/components/popovers/第一部分根据文档初始化弹出窗口: https : //getbootstrap.com/docs/4.0/components/popovers/
  • The first "if" in the second section checks whether the clicked element is a descendant of #my-popover-trigger.第二部分中的第一个“if”检查被点击的元素是否是#my-popover-trigger 的后代。 If that is true, it toggles the popover (it handles the click on the trigger).如果这是真的,它会切换弹出窗口(它处理触发器上的点击)。
  • The second "if" in the second section checks whether the clicked element is a descendant of the popover content class which was defined in the init template.第二部分中的第二个“if”检查被点击的元素是否是在 init 模板中定义的 popover 内容类的后代。 If it is not this means that the click was not inside the popover content, and the popover can be hidden.如果不是,则表示点击不在弹出框内容内,可以隐藏弹出框。

Try data-trigger="focus" instead of "click" .尝试data-trigger="focus"而不是"click"

This solved the problem for me.这为我解决了这个问题。

jQuery(':not(.popup-marker)').once().click(function(){
   jQuery('.popup-marker').hide(); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM