jQuery Bootstrap 工具提示 - 单击另一个工具提示时隐藏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17274130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:44:22  来源:igfitidea点击:

Bootstrap Tooltip - Hide when another tooltip is click

javascriptjquerytwitter-bootstraptooltip

提问by user1381806

I hope someone can help.

我希望有人能帮帮忙。

I'm trying to hide the tooltip when another tooltip icon is clicked. It works but when I decide to click the last tooltip again it 'flashes' the tooltip.

当单击另一个工具提示图标时,我试图隐藏工具提示。它有效,但是当我决定再次单击最后一个工具提示时,它会“闪烁”工具提示。

var Hastooltip = $('.hastooltip');
HasTooltip.on('click', function(e) {
     e.preventDefault();
     HasTooltip.tooltip('hide');
}).tooltip({
     animation: true
}).parent().delegate('.close', 'click', function() {
     HasTooltip.tooltip('hide');
});

HTML

HTML

<a href="#" class="hastooltip" data-original-title="Lorem ipsum dolor sit amet, consectetur adipisicing elit.">
    <h3>Info 1</h3>
</a>

<a href="#" class="hastooltip" data-original-title="Lorem ipsum dolor sit amet, consectetur adipisicing elit.">
    <h3>Info 2</h3>
</a>

If it helps a following markup is added to the DOM when the user clicks on the button to display the tooltip.

如果有帮助,当用户单击按钮以显示工具提示时,会将以下标记添加到 DOM。

<div class="tooltip"</div>

采纳答案by user694844

You need to check if the tooltip is showing and toggle its visibility manually. This is one way of doing it.

您需要检查工具提示是否显示并手动切换其可见性。这是一种方法。

$(function() {
  var HasTooltip = $('.hastooltip');
  HasTooltip.on('click', function(e) {
    e.preventDefault();
    var isShowing = $(this).data('isShowing');
    HasTooltip.removeData('isShowing');
    if (isShowing !== 'true')
    {
      HasTooltip.not(this).tooltip('hide');
      $(this).data('isShowing', "true");
      $(this).tooltip('show');
    }
    else
    {
      $(this).tooltip('hide');
    }

  }).tooltip({
    animation: true,
    trigger: 'manual'
  });
});

回答by kiprainey

This can be handled more easily than the above answers indicate. You can do this with a single line of javascript in your show handler:

这可以比上述答案更容易处理。您可以在显示处理程序中使用一行 javascript 来完成此操作:

$('.tooltip').not(this).hide();

Here's a complete example. Change 'element' to match your selector.

这是一个完整的例子。更改“元素”以匹配您的选择器。

$(element).on('show.bs.tooltip', function() {
    // Only one tooltip should ever be open at a time
    $('.tooltip').not(this).hide();
});

The same technique is suggested for closing popovers in this SO thread:

建议使用相同的技术来关闭此 SO 线程中的弹出窗口:

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

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

回答by Радислав Ялилов

I slightly modified the code of kiprainey

我稍微修改了kiprainey的代码

const $tooltip = $('[data-toggle="tooltip"]');
 $tooltip.tooltip({
   html: true,
   trigger: 'click',
   placement: 'bottom',
 });
 $tooltip.on('show.bs.tooltip', () => {
   $('.tooltip').not(this).remove();
 });

I use remove() instead of hide()

我使用 remove() 而不是 hide()

回答by Jochen

I went into the same problem for regular tooltips. On an iPhone, they do not go away when clicking on the body (i.e. somewhere else).

对于常规工具提示,我遇到了同样的问题。在 iPhone 上,当点击身体(即其他地方)时,它们不会消失。

My solution is that when you click on the tooltip itself, it hides. IMHO, this should be integrated in bootstrap distribution, because it is few code with a big effect.

我的解决方案是,当您单击工具提示本身时,它会隐藏。恕我直言,这应该集成在引导程序分发中,因为它是少数代码效果大的。

When you have access to bootstrap sources, add

当您有权访问引导程序源时,添加

this.tip().click($.proxy(this.hide, this))

as the last line in method Tooltip.prototype.init in file tooltip.js:

作为文件 tooltip.js 中 Tooltip.prototype.init 方法的最后一行:

Tooltip.prototype.init = function (type, element, options) {
this.enabled  = true
this.type     = type
this.$element = $(element)
this.options  = this.getOptions(options)

var triggers = this.options.trigger.split(' ')

for (var i = triggers.length; i--;) {
  var trigger = triggers[i]

  if (trigger == 'click') {
    this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
  } else if (trigger != 'manual') {
    var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focus'
    var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'

    this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
    this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
  }
}

this.options.selector ?
  (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
  this.fixTitle()

 // Hide tooltip when clicking on it. Useful for mobile devices like iPhone where eventOut
 // (see above) on $element is not triggered and you don't get rid of the tooltip anymore.
 this.tip().click($.proxy(this.hide, this))
  }

If you do not have the sources at hand, you can achieve the same effect with the following:

如果您手头没有资源,可以使用以下方法实现相同的效果:

    $(function()
    {
        // Apply tooltips
        var hasTooltip = $("[data-toggle='tooltip']").tooltip();

        // Loop over all elements having a tooltip now.
        hasTooltip.each(function()
           {
               // Get the tooltip itself, i.e. the Javascript object
               var $tooltip = $(this).data('bs.tooltip');

               // Hide tooltip when clicking on it
               $tooltip.tip().click($.proxy($tooltip.hide, $tooltip))
           }
        );
    });

For me, that makes a good user experience on an iPhone: Click on the element to see the tooltip. Click on the tooltip that it goes away.

对我来说,这在 iPhone 上提供了良好的用户体验:单击元素以查看工具提示。单击它消失的工具提示。

回答by Ketwaroo D. Yaasir

I was looking for a solution to this problem as well and it seems to me that $('.tooltip').not(this).hide();will bypass any bootstrap show, shown, hideor hiddenevents you may have attached to the trigger element. After some thought, I've come up the following code allows for somewhat more transparent handling of attached events.

我也在寻找这个问题的解决方案,在我看来,它$('.tooltip').not(this).hide();可以绕过您可能附加到触发器元素的任何 bootstrap showshownhidehidden事件。经过一番思考,我想出了以下代码允许对附加事件进行更透明的处理。

Note: tested on firefox and chrome only but should work fine in theory.

注意:仅在 Firefox 和 chrome 上测试过,但理论上应该可以正常工作。

$(document).ready(function() {

  $('[data-toggle="popover"]').popover();


  $(document).on('show.bs.popover', function(event) {
    // could use [data-toggle="popover"] instead
    // using a different selector allows to have different sets of single instance popovers.
    $('[data-popover-type="singleton"]').not(event.target).each(function(key, el) {
      $(el).popover('hide'); // this way everything gets propagated properly
    });
  });

  $(document).on('click', function(event) {
    // choose to close all popovers if clicking on anything but a popover element.
    if (!($(event.target).data('toggle') === "popover" /* the trigger buttons */ 
          || $(event.target).hasClass('popover') /* the popup menu */
          || $(event.target).parents('.popover[role="tooltip"]').length /* this one is a bit fiddly but also catches child elements of the popup menu. */ )) {
      
      $('[data-toggle="popover"]').popover('hide');
    }
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />



<button type="button" class="btn btn-danger" data-placement="bottom" data-toggle="popover" title="Popover One" data-content="Popover One Content. `focus` trigger still behaves as expected" data-trigger="focus" data-popover-type="singleton">Popover One</button>

<button type="button" class="btn btn-warning" data-placement="bottom" data-toggle="popover" title="Popover Two" data-content="Popover Two Content. for other triggers, clicking on content does not close popover" data-trigger="click" data-popover-type="singleton">Popover Two</button>

<button type="button" class="btn btn-success" data-placement="bottom" data-toggle="popover" title="Popover Three" data-content="Popover Three Content. clicking outside popover menu closes everything" data-trigger="click" data-popover-type="singleton">Popover Three</button>

fiddle example here: http://jsfiddle.net/ketwaroo/x6k1h7j4/

这里的小提琴示例:http: //jsfiddle.net/ketwaroo/x6k1h7j4/

回答by dh-phuong

$('[data-toggle=tooltip],[rel=tooltip]').tooltip({ 
        container: 'body' }).click(function () {
        $('.tooltip').not(this).hide();
    });

回答by donbrae

Re kiprainey's answer, there is an issue in that once a tooltip has been hidden, it needs to be clicked twice to be shown again. I got around this by using tooltip('hide')instead of hide():

Re kiprainey's answer,存在一个问题,即工具提示被隐藏后,需要单击两次才能再次显示。我通过使用tooltip('hide')而不是hide()

$(element).on('show.bs.tooltip', function() {
    // Only one tooltip should ever be open at a time
    $('.tooltip').not(this).tooltip('hide');
});

回答by Eric

Thanks Jochen for the "Iphone" click on tooltip to close solution, exactly what I was looking for.

感谢 Jochen 的“Iphone”单击工具提示以关闭解决方案,这正是我正在寻找的。

As for the original request (prevent multiple tooltip fonctionnality is an obvious need when you are asked to implement click tooltip instead of rollover ones), here is my take:

至于原始请求(当您被要求实现点击工具提示而不是滚动提示时,防止多个工具提示功能是一个明显的需要),这是我的看法:

Just after , show: function () {add:

紧接着 , show: function () {添加:

  // HACK BEGIN
  // Quick fix. Only one tooltip should be visible at all time.
  // prototype level property are accessible to all instances so we use one to track last opened tooltip (ie. current this).
  if ( (Tooltip.prototype.currentlyShownTooltip != null) || (Tooltip.prototype.currentlyShownTooltip != undefined) ) {
    // Close previously opened tooltip.
    if (Tooltip.prototype.currentlyShownTooltip != this) { // Conflict with toggle func. Re-show.
        Tooltip.prototype.currentlyShownTooltip.hide();
        Tooltip.prototype.currentlyShownTooltip = null
    }
  }
  // Keep track of the currently opened tooltip.
  Tooltip.prototype.currentlyShownTooltip = this
  // HACK END