北京城乡建设部网站,做原创的网站,网络建设的流程网站,建设银行网站查询余额Switch开关#xff1a;根据需求可知#xff0c;Switch开关只有两种选择#xff0c;true或false。所以我们想到HTML的checkbox控件#xff0c;用它来做。 input idswitch typecheckbox classswitch /但是在浏览器中#xf…Switch开关根据需求可知Switch开关只有两种选择true或false。所以我们想到HTML的checkbox控件用它来做。
input idswitch typecheckbox classswitch /但是在浏览器中checkbox是有固定形状的对勾所以我们并不能直接修改checkbox的样式。那我们该修改一个什么东西的样式变成开关呢所以我们联想到 label 标签为什么呢因为label标签的for属性可以绑定表单控件点击label标签就相当于你点击了绑定的那个控件。
label forswitchtest/label废话不多说直接上完整代码
!DOCTYPE html
htmlheadmeta charsetutf-8 /title/titlelink relstylesheet hrefcss/test.css //headbodydiv classswitch-containerinput idswitch typecheckbox classswitch /label forswitch onclicktest()/label/divscriptvar test function(){console.log(!document.getElementById(switch).checked ? 选中 : 未选中);}/script/body
/html/*开关的大小*/
.switch-container {height: 15px;width: 30px;
}/*设置checkbox不显示*/
.switch {display: none;
}/*设置label标签为椭圆状*/
label {display: block;background-color: #EEEEEE;height: 100%;width: 100%;cursor: pointer;border-radius: 25px;
}/*在label标签内容之前添加如下样式形成一个未选中状态*/
label:before {content: ;display: block;border-radius: 25px;height: 100%;width: 15px;background-color: white;opacity: 1;box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);-webkit-transition: all 0.2s ease;
}/*在label标签内容之后添加如下样式形成一个选中状态*/
label:after {position: relative;top: -15px;left: 15px;content: ;display: block;border-radius: 25px;height: 100%;width: 15px;background-color: white;opacity: 0;box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);-webkit-transition: all 0.2s ease;
}/* ~ 兄弟选择符。p~ul 位于 p 元素之后的所有 ul 元素
*//*选中后选中样式显示*/
#switch:checked~label:after {opacity: 1;
}/*选中后未选中样式消失*/
#switch:checked~label:before {opacity: 0;
}/*选中后label的背景色改变*/
#switch:checked~label {background-color: green;
}如果你用了sass可以设置变量来改变你的开关的大小。
$switchHeight: 30px;
$switchWidth: 60px; /*改变大小只需要改变这个两个的值后面会用到这两个值*/
.switch-container {height: $switchHeight;width: $switchWidth;margin-bottom: 5px;.switch {display: none;}label {display: block;background-color: #EEEEEE;height: 100%;width: 100%;cursor: pointer;border-radius: 25px;}label:before {content: ;display: block;border-radius: 25px;height: 100%;width: $switchHeight;background-color: white;opacity: 1;box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);-ms-transition: all 0.2s ease; /* IE 9 */-moz-transition: all 0.2s ease; /* Firefox */-webkit-transition: all 0.2s ease;/* Safari and Chrome */-o-transition: all 0.2s ease; /* Opera */}label:after {position: relative;top: -$switchHeight;left: $switchHeight;content: ;display: block;border-radius: 25px;height: 100%;width: $switchHeight;background-color: white;opacity: 0;box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);-ms-transition: all 0.2s ease; /* IE 9 */-moz-transition: all 0.2s ease; /* Firefox */-webkit-transition: all 0.2s ease;/* Safari and Chrome */-o-transition: all 0.2s ease; /* Opera */}#switch:checked~label:after {opacity: 1;}#switch:checked~label:before {opacity: 0;}#switch:checked~label {background-color: green;}
}