CSS寫一個開關按鈕可以用到偽元素和transition動畫效果。以下是示例代碼:
<label class="switch"> <input type="checkbox"> <div class="slider round"></div> </label> .switch { position: relative; display: inline-block; width: 60px; height: 34px; margin-bottom: 0; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { transform: translateX(26px); } .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; }
以上代碼中,我們利用了label標簽與input標簽相結合的方式,實現了一個簡單的開關按鈕。使用偽元素:before創建了按鈕的圓形滑塊,并通過transition動畫效果使其平滑滑動。