Disable Twitter Bootstrap Button Group

2019-02-21 22:29发布

问题:

I have a button group on a page that is used for a selection. After the selection is made I want the button group to still be visible so the user can see the selection they made, but I don't want them to be able to use it anymore. Is there a way to disable to the button group?

<div class="btn-group-vertical">
    <button type="button" class="btn btn-primary btn-lg">Option 1</button>
    <button type="button" class="btn btn-primary btn-lg">Option 2</button>
    <button type="button" class="btn btn-primary btn-lg">Option 3</button>
</div>

回答1:

You can use the disabled attribute on the buttons to disable their use, as described in the Bootstrap docs. It essentially involves adding the attribute 'disabled' to the button element, like so;

<div class="btn-group-vertical">
    <button type="button" class="btn btn-primary btn-lg" disabled="disabled">Option 1</button>
    <button type="button" class="btn btn-primary btn-lg" disabled="disabled">Option 2</button>
    <button type="button" class="btn btn-primary btn-lg" disabled="disabled">Option 3</button>
</div>

You can use jQuery to dynamically add this attribute once you've done whatever you want to do

$('.btn-group-vertical button').attr('disabled','disabled');

And if you wanted to re-enable it

$('.btn-group-vertical button').removeAttr('disabled');

Bear in mind that the above would apply this behaviour to all button groups with this class name. If you don't want that you'll need to add an ID to the btn group div and use that in the jQuery selector.



回答2:

I wanted to keep the styling too, So I left out the disabled field and just counter-acted the CSS with a new class display-only:

<div class='btn-group display-only' data-toggle='buttons'>      
    <label class='btn btn-default button-array'>Friday PM</label>
    <label class='btn btn-default button-array'>Saturday AM</label>
    <label class='btn btn-default button-array'>Graduation</label>
    <label class='btn btn-default button-array'>Saturday PM</label>
    <label class='btn btn-default button-array'>Sunday AM</label>
    <label class='btn btn-default button-array'>Sunday PM</label>
    <label class='btn btn-default button-array'>Monday AM</label>
</div> 

And the CSS:

.btn-group.display-only label.btn {
    pointer-events: none;
    cursor: not-allowed;
}
.btn-group.display-only label.btn.active {
    opacity: 1;
    color: #333;
    background-color: #e6e6e6;
    border-color: #adadad;webkit-box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
    box-shadow: inset 0 3px 5px rgba(0,0,0,.125);
}

..Seems to work well for me.



回答3:

Before v4.0.0, Bootstrap Toggle buttons do not honor .disabled or [disabled] :

https://github.com/twbs/bootstrap/issues/21237