DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
用 CSS3 與 checkbox 模擬 jQuery 的 show、fadeIn 與 slideDown
編輯:布局實例     

這個技巧的核心是 :checked 偽類加上相鄰兄弟選擇器 ~:把真正的 <input type="checkbox"> 藏起來,用 <label> 充當切換按鈕,再靠勾選狀態去控制後方元素的樣式。全程零 JavaScript。

共同 HTML 結構

<div id="box">
  <input type="checkbox" id="sh" />
  <label for="sh">show/hide</label>
  <div id="shbox">
    點擊上面的 show/hide 切換顯示
  </div>
</div>

關鍵是 label 的 for 必須對應 checkbox 的 id,而 checkbox 本身用絕對定位推到畫面外。

show() / hide():控制 display

#box {
  position: relative;
}
#box *:not(#shbox) {
  display: inline-block;
}
input {
  position: absolute;
  left: -10000000px;
}
:checked ~ #shbox {
  display: none;
}
label {
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid green;
  position: absolute;
  left: 0;
  cursor: pointer;
  border-radius: 5px;
}
#shbox {
  background: #ccc;
  color: red;
  width: 200px;
  height: 200px;
  border: 1px solid blue;
  box-sizing: border-box;
  padding: 50px;
  position: absolute;
  top: 50px;
}

fadeIn() / fadeOut():控制 opacity

HTML 沿用上面那份,CSS 只要改一行:

:checked ~ #shbox {
  opacity: 0;
}

jQuery 的 fadeIn 可以控制速度,CSS 這邊加上 transition 就能模擬:

#shbox {
  transition: opacity 2s;
}

slideUp() / slideDown():控制高度

:checked ~ #shbox {
  height: 0;
}

#shbox {
  background: #ccc;
  overflow-y: hidden;   /* 連內容一起隱藏 */
  color: red;
  width: 200px;
  height: 200px;
  box-sizing: border-box;
  transition: all 2s;
  position: absolute;
  top: 50px;
}

這裡三個細節要注意:overflow-y: hidden 是必要的,否則框縮起來了文字還露在外面;transition 負責補上中間的過渡;同時要拿掉 border,因為高度歸零時邊框仍會佔位。

該不該在專案裡這麼做

這套做法很適合用於「純展示型」的收合面板,特別是你不希望為一個簡單的開關載入 jQuery 的情況。但它有兩個明顯限制:一是狀態無法用程式控制(沒辦法在 JS 裡「程式化地」勾選它,除非你反過的去操作 checkbox);二是無障礙性較差,螢幕閱讀器對這種偽裝的互動元件理解有限。互動邏輯一旦變複雜,還是回到正規的 JS 加 aria-expanded 比較穩妥。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved