Toggle Twitter Bootstrap button class when active

前端 未结 3 685
野性不改
野性不改 2020-12-31 05:13

In twitter bootstrap, I was looking for a way to allow a button to be the default color when not active. Once a button is active, I wanted to change the color of it. I loo

3条回答
  •  我在风中等你
    2020-12-31 06:15

    I don't think, that any JS is really necessary. I believe that this can by done purely by CSS and data attributes.

    Yes, it involves a little CSS duplication, but still better than sometimes glitchy javascript.

    1. Add data attribute data-active-class to button,
    2. Add custom CSS for all classes (example of one for readability; colors are taken from already existing classes "primary", "success", and so on)

      .btn.active[data-active-class="primary"] {
          color: #fff;
          background-color: #286090;
          border-color: #204d74;
      }
      

    Inactive button will render as usual, active based on data-* attribute will render by this^^ CSS.

    JSFiddle with complete CSS

    Edit: When using SASS or LESS the colors can/should be used from variables already defined by Bootstrap... that solves the duplicating problem.

提交回复
热议问题