Bootstrap工具提示 - 当点击另一个工具提示时隐藏

36

我希望有人能帮忙。

我正在尝试在单击另一个工具提示图标时隐藏工具提示。虽然它可以正常工作,但当我决定再次单击最后一个工具提示时,它会“闪烁”出现。

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

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

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

<div class="tooltip"</div>

无法理解你的问题..是提示框还是弹出框?因为当鼠标离开时,提示框会消失。 - sangram parmar
使用工具提示。http://twitter.github.com/bootstrap/javascript.html#tooltips - 我希望如果工具提示可见并且单击了另一个工具提示,则可见的工具提示将隐藏。 - user1381806
你能同时发布你的HTML代码吗? - Carol Skelly
当然,我已经为您添加了。 - user1381806
10个回答

55

与上面的答案所示相比,这可以更轻松地处理。您可以在show处理程序中使用一行JavaScript代码来完成此操作:

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

以下是完整的示例。将“element”更改为与您的选择器匹配。

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

在这个 SO 帖子中,建议使用相同的技术来关闭弹出框:

如何通过页面上任何(其他)位置的单击关闭 Twitter Bootstrap 弹出框?


3
太聪明了,应该成为新的被接受的答案!谢谢! - Alveoli
1
正是我一直在寻找的。 $('.tooltip').tooltip('hide'); 没有起作用,但是 $('.tooltip').not(this).hide(); 成功了! - C0ZEN
1
这应该是答案。 - Paul
很不幸,当同时使用hoverclick作为触发器时,这会出现一些问题。 - dude
4
除了一点,这个对我有用。一旦工具提示被隐藏,要再次显示它,我必须点击两次。 - JayJay

15

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

$(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'
  });
});

你本可以简单地移除动画来完成它,但那样会改变外观。 - user694844
是否可以切换工具提示?如果我点击已经设置为true的相同工具提示,它将被设置为隐藏。 - user1381806
真是一团糟!看起来像是用大锤打苍蝇的经典例子。 - Fr0zenFyr

6
我稍微修改了kiprainey的代码。
const $tooltip = $('[data-toggle="tooltip"]');
 $tooltip.tooltip({
   html: true,
   trigger: 'click',
   placement: 'bottom',
 });
 $tooltip.on('show.bs.tooltip', () => {
   $('.tooltip').not(this).remove();
 });

我使用remove()代替hide()


如果你试图摆脱动态替换元素上的工具提示,那么使用remove()更好。 - kjdion84
太好了,它运行良好。hide()确实隐藏元素但不会再次显示。但是remove()没有这个问题。我已经在元素中同时使用了tooltip和confirmation,使用remove()非常有用。 - Web_Developer

3

我遇到了普通工具提示的同样问题。在iPhone上,当单击页面的其他位置时,它们不会消失。

我的解决方案是,当你单击提示本身时,它会隐藏。在我看来,这应该被集成在bootstrap分发中,因为它只有很少的代码却有很大的效果。

当你可以访问bootstrap源代码时,请添加:

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

在文件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))
  }

如果您手头没有源代码,可以通过以下方式达到相同的效果:

    $(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))
           }
        );
    });

对我而言,在iPhone上获得良好的用户体验意味着:点击元素以查看工具提示,再次点击工具提示即可关闭。

3

根据kiprainey的回答,有一个问题是一旦隐藏了工具提示,需要点击两次才能再次显示。我通过使用tooltip('hide')代替hide()来解决这个问题:

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

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

不要只贴链接作为答案,加上一些文字解释如何帮助OP解决当前的问题。谢谢。 - ρяσѕρєя K

1
我也在寻找解决此问题的方法,似乎 $('.tooltip').not(this).hide(); 可以绕过任何与触发元素相关的 bootstrap showshownhidehidden 事件。经过一番思考,我想到了以下代码,可以更透明地处理附加事件。
注意:仅在 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示例:http://jsfiddle.net/ketwaroo/x6k1h7j4/


0
我使用类名来添加工具提示并删除了使用类名,它现在正常工作。
添加工具提示
$('.tooltips').tooltip({
      animation: true
      , container: 'body'
      , html: true
      , placement: 'auto'
      , trigger: 'focus hover'
  });

隐藏工具提示

$('.tooltips').tooltip('hide');

0

感谢Jochen提供的"Iphone"点击提示关闭解决方案,正是我所需要的。

至于原始请求(当您被要求实现点击提示而不是悬停提示时,防止多个提示功能是一个明显的需求),这是我的建议:

,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

0

我会给你一个好的解决方案,还有额外的奖金

        //save the tooltip in variable (change the selector to suit your tooltip)
        var $tooltips = $('a[data-toggle="tooltip"]');
        
        //initialise the tooltip with 'click' trigger  
        $tooltips.tooltip({
            animated: 'fade',
            placement: 'top',
            trigger: 'click',
            delay: { "show": 100, "hide": 100 }
        });
        
        //Here is the juicy bit: when a tooltip is opened it 
        //it creates an 'aria-describedby' with the id of the tooltip
        //opened we can leverage this to turn off all others but current

        $tooltips.on('click', function () {
            var toolTipId = $(this).attr('aria-describedby');
            $('.tooltip').not('#'+ toolTipId).tooltip('hide');
        });

        //But wait theres more! if you call now we chuck in a free close on X seconds event!
        $tooltips.on('shown.bs.tooltip', function (e) {
            //Auto hide after 7 seconds
            setTimeout(function () {
                $(e.target).tooltip('hide');
            }, 7000);
        });

        //call now! XD

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