
今天來講下css中的開關按鈕這個特效,在實際開發和平常的網頁中都很常見,
大家先來看看實作的效果:
這是開關按鈕全部選中的時候

這是開關按鈕全部關閉的時候,其中切換的時候會有一些影片特效,

實作的原理步驟如下:
1.先設定一個label包裹一個checkbox元素和一個子div,其中checkbox設定為不顯示
2.子代div有一個before元素:

這里要注意下!
3.雖然checkbox不顯示,但是當點擊的時候還是會有屬性改變,因此我們可以利用這個屬性改變設定一些值,詳細的步驟都在原始碼里,原始碼有很詳細的注釋,
原始碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>開關按鈕</title>
<style>
.switch {
/* 定義position為relative,子元素的absolute在這里作參照 */
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
/* 隱藏input的顯示 */
display: none;
}
.slider {
position: absolute;
cursor: pointer;
/* 撐滿外層的div標簽 */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
/* 設定顯示時候的影片 */
-webkit-transition: .4s;
transition: .4s;
}
/* 設定子div前面的元素 */
.slider:before {
position: absolute;
/* before的內容為空白 */
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
/* 設定按鈕點擊的時候的影片效果 */
-webkit-transition: .4s;
transition: .4s;
}
/* 兩個屬性同時存在的時候的css樣式 */
input:checked+.slider {
background-color: teal;
}
input:focus+.slider {
box-shadow: 0 0 1px teal;
}
/* 設定before元素的平移影片 */
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* 設定下面一組按鈕的圓角 */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
</head>
<body>
<label class="switch">
<input type="checkbox">
<div class="slider"></div>
</label>
<label class="switch">
<input type="checkbox" checked>
<div class="slider"></div>
</label><br><br>
<label class="switch">
<input type="checkbox">
<div class="slider round"></div>
</label>
<label class="switch">
<input type="checkbox" checked>
<div class="slider round"></div>
</label>
</body>
</html>
喜歡的話,記得點贊關注哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/229871.html
標籤:其他
