知識點:
1.css3 transition的使用
2.label 和 checkbox的綁定
3.absolute與relative的使用
4.css3偽元素
講解:
1.css3 transition
參考資料:http://www.w3school.com.cn/cssref/pr_transition.asp
個人理解:主要用于實現html元素的屬性進行漸進式的變化。所以必輸元素有三:屬性 漸變時間長度 漸變效果
2.label和checkbox的綁定
參考資料:http://www.w3school.com.cn/tags/att_label_for.asp
個人理解:分為隱式和顯示兩種。通過id進行綁定,將label綁定到checkbox,能夠讓點擊label時,讓checkbox也獲得焦點。
3.absolute和relateive的使用
參考資料:http://www.lxweimin.com/p/a3da5e27d22b http://www.lxweimin.com/p/07eb19957991
個人理解:absolute讓元素脫離文檔流,并且父元素徹底無法感知加了absolute的元素。relative給absolute添加了天花板,在relative的范圍內變化。
設計思路:
開關按鈕存在開關兩種狀態,最適合模擬的元素為checkbox。checkbox比較丑,所以我們需要保留元素功能,隱藏元素,同時還能夠獲得和丟失checkbox的狀態。因此,需要引入label,作為顯示。label作為容器,內部添加兩個span。一個是用來顯示on/off,一個用來表示開關的小按鈕。on/off作為文字進行滑動效果,小按鈕也引入滑動效果。
代碼實現:
<html>
<head>
<title>switch</title>
<style type="text/css">
.switch{
display: block;
float: left;
position: relative;
width: 200px;
height: 50px;
}
#test{
display: none;
}
.switch-label{
display: block;
overflow: hidden;
width: 160px;
height: 50px;
border-radius: 8px;
border: 1px solid gray;
}
.switch-txt {
display: block;
width: 200%;
border-radius: 8px;
height: 50px;
transition:margin 0.3s ease-in;
}
.switch-txt::before,.switch-txt:after {
display: block;
float: right;
text-align: center;
line-height: 50px;
width: 50%;
height: 50px;
}
.switch-txt::before {
content: attr(data-on);
background-color: green;
}
.switch-txt::after {
content: attr(data-off);
background-color: gray;
}
.switch-switch {
display: block;
position: absolute;
width: 20px;
border-radius: 8px;
top: 0;
bottom: 0;
right: 89%;
background-color: white;
transition: all 0.3s ease-in;
}
#test:checked + .switch-label .switch-switch {
right:40px;
}
#test:checked + .switch-label .switch-txt {
margin-left: -100%;
}
</style>
</head>
<body>
<div class="switch">
<input id="test" type="checkbox">
<label for="test" class="switch-label">
<span class="switch-txt" data-on="ON" data-off="OFF"></span>
<span class="switch-switch"></span>
</label>
</div>
</body>
</html>
實現效果: