這個技巧的核心是 :checked 偽類加上相鄰兄弟選擇器 ~:把真正的 <input type="checkbox"> 藏起來,用 <label> 充當切換按鈕,再靠勾選狀態去控制後方元素的樣式。全程零 JavaScript。
<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 本身用絕對定位推到畫面外。
#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;
}
HTML 沿用上面那份,CSS 只要改一行:
:checked ~ #shbox {
opacity: 0;
}
jQuery 的 fadeIn 可以控制速度,CSS 這邊加上 transition 就能模擬:
#shbox {
transition: opacity 2s;
}
: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 比較穩妥。