CSS實現(xiàn)input開關按鈕功能,只需要用到偽類選擇器和transform屬性即可:
.switch-checkbox { display: none; } .switch-label { display: inline-block; cursor: pointer; position: relative; height: 28px; width: 56px; background-color: #ccc; border-radius: 28px; } .switch-label:before, .switch-label:after { content: ""; position: absolute; top: 0; left: 0; width: 50%; height: 100%; } .switch-label:before { background-color: #fff; border-radius: 28px; transform: translateX(0); transition: transform 0.3s ease-in-out; } .switch-label:after { border-radius: 50%; background-color: gray; box-shadow: 0 0 2px rgba(0, 0, 0, 0.3); transform: translateX(100%); transition: transform 0.3s ease-in-out; } .switch-checkbox:checked + .switch-label:before { transform: translateX(100%); } .switch-checkbox:checked + .switch-label:after { transform: translateX(0); }
上面的代碼中,用了一個隱藏的checkbox標簽,并用偽類選擇器:before和:after來模擬開關按鈕的狀態(tài),然后用transform屬性實現(xiàn)了開關切換的動畫效果。最后通過checkbox的:checked狀態(tài)來控制偽類選擇器的transform屬性的值,來實現(xiàn)開關狀態(tài)的切換。