How to enable Bootstrap tooltip on disabled button?

后端 未结 18 2462
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 23:18

I need to display a tooltip on a disabled button and remove it on an enabled button. Currently, it works in reverse.

What is the best way to invert this behaviour?

18条回答
  •  庸人自扰
    2020-11-29 00:15

    This is what myself and tekromancr came up with.

    Example element:

    Press Me
    

    note: the tooltip attributes can be added to a separate div, in which the id of that div is to be used when calling .tooltip('destroy'); or .tooltip();

    this enables the tooltip, put it in any javascript that is included in the html file. this line might not be necessary to add, however. (if the tooltip shows w/o this line then don't bother including it)

    $("#element_id").tooltip();
    

    destroys tooltip, see below for usage.

    $("#element_id").tooltip('destroy');
    

    prevents the button from being clickable. because the disabled attribute is not being used, this is necessary, otherwise the button would still be clickable even though it "looks" as if it is disabled.

    $("#element_id").click(
      function(evt){
        if ($(this).hasClass("btn-disabled")) {
          evt.preventDefault();
          return false;
        }
      });
    

    Using bootstrap, the classes btn and btn-disabled are available to you. Override these in your own .css file. you can add any colors or whatever you want the button to look like when disabled. Make sure you keep the cursor: default; you can also change what .btn.btn-success looks like.

    .btn.btn-disabled{
        cursor: default;
    }
    

    add the code below to whatever javascript is controlling the button becoming enabled.

    $("#element_id").removeClass('btn-disabled');
    $("#element_id").addClass('btn-success');
    $('#element_id).tooltip('destroy');
    

    tooltip should now only show when the button is disabled.

    if you are using angularjs i also have a solution for that, if desired.

提交回复
热议问题