1. 程式人生 > >Bootstrap學習筆記(五)選單、按鈕及導航

Bootstrap學習筆記(五)選單、按鈕及導航

單個按鈕在Web頁面中的運用有時候並不能滿足我們的業務需求,常常會看到將多個按鈕組合在一起使用,比如富文字編輯器裡的一組小圖示按鈕等。那麼在這一節中,我們主要向大家介紹Bootstrap框架為大家提供的按鈕組元件。

原始碼查詢:

按鈕組也是一個獨立的元件,所以可以找到對應的原始碼檔案:

  ☑  LESS版本:對應的原始檔為buttons.less

  ☑  Sass版本:對應的原始檔為_buttons.scss

  ☑  CSS版本:對應bootstrap.css檔案第3131行~第3291行

使用方法:

按鈕組和下拉選單元件一樣,需要依賴於button.js外掛才能正常執行。不過我們同樣可以直接只調用bootstrap.js檔案。因為這個檔案已集成了button.js外掛功能。

對於結構方面,非常的簡單。使用一個名為“btn-group”的容器,把多個按鈕放到這個容器中。如下所示:

<div class="btn-group">
  <button type="button" class="btn btn-default">
     <span class="glyphicon glyphicon-step-backward"></span>
  </button>
   …
  <button type="button" class="btn btn-default">
     <span class="glyphicon glyphicon-step-forward"></span>
  </button>
</div>

執行效果如下所示:

除了可以使用<button>元素之外,還可以使用其他標籤元素,比如<a>標籤。唯一要保證的是:不管使用什麼標籤,“.btn-group”容器裡的標籤元素需要帶有類名“.btn”。

按鈕組實現原始碼如下:

/*檢視bootstrap.css檔案第3131行~第3161行*/

.btn-group,
.btn-group-vertical {
  position: relative;
  display: inline-block;
  vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
  position: relative;
  float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
  z-index: 2;
}
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus {
  outline: none;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
   margin-left: -1px;
}

從效果圖上我們可以看出,按鈕組四個角都是圓角(支援CSS3的瀏覽器),但有的小夥伴會問,我們平常製作網頁時每個按鈕都是帶有圓角,而在按鈕組中的按鈕,除了第一個和最後一個具有邊上的圓角之外,其他的按鈕沒有圓角,其實實現方法非常簡單:

  1、預設所有按鈕都有圓角

  2、除第一個按鈕和最後一個按鈕(下拉按鈕除外),其他的按鈕都取消圓角效果

  3、第一個按鈕只留左上角和左下角是圓角

  4、最後一個按鈕只留右上角和右下角是圓角

對應的原始碼如下:

/*檢視bootstrap.css檔案第3174行~第3203行*/

.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
  border-radius: 0;
}
.btn-group > .btn:first-child {
  margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
.btn-group > .btn-group {
  float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
  border-radius: 0;
}
.btn-group > .btn-group:first-child> .btn:last-child,
.btn-group > .btn-group:first-child> .dropdown-toggle {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.btn-group > .btn-group:last-child> .btn:first-child {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}