这是基础篇,所以要讲得仔细点,首先,我们有时候会看到这么一个需求:
这是一个很常见的控件,所以很有必要去掌握他,而我们需要的就是用到最常用的input标签,
<input type="checkbox">
因为他有“切换”功能,可是又有一个问题,我们怎么把那个带有√号的框框改造成一个带有圆圈的,高大上的方块呢?
显然不能在他上面动手脚,这时候就要想到另外一个常和input一起使用的label标签了,因为他有“for”属性,可以实现将焦点转移到input标签上,而且他本身就是一个“空白”,可以很容易改造成我们所需要的类型,然后,对于checkbox的选中状态,又是我们事件处理的好方法,所以checkbox是特佳的选择,思路讲完了,希望大家能整理成自己的代码:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style_all.css" />
<style>
</style>
</head>
<body>
<input type="checkbox" class="widget_switch_checkbox" id="widget_switch_checkbox">
<label for="widget_switch_checkbox" class="widget_switch_label">
<span class="widget_switch_circle"></span>
</label>
<script>
document.querySelector("input.widget_switch_checkbox").addEventListener("click", function() {
if(document.querySelector("input.widget_switch_checkbox").checked) {
console.log(new Date().getTime());
console.log("选中状态");
}
});
</script>
</body>
</html>
css文件如下:
/*开关按钮:模板
*
* 注意:此处尺寸设置死的
*
*
<div id="container">
<input type="checkbox" class="widget_switch_checkbox" id="widget_switch_checkbox">
<label for="widget_switch_checkbox" class="widget_switch_label">
<span class="widget_switch_circle"></span>
</label>
</div>
*/
/*点击事件则是使用:
* document.querySelector("input.widget_switch_checkbox").addEventListener("click", function() {
if(document.querySelector("input.widget_switch_checkbox").checked) {
console.log(new Date().getTime());
console.log("选中状态");
}
});
*/
.widget_switch_checkbox {
display: none;
}
.widget_switch_label {
margin-top: 5px;
background-color: grey;
display: inline-block;
position: relative;
height: 30px;
width: 80px;
border-radius: 1000px;
box-shadow: 0 0 2px black;
}
.widget_switch_checkbox:checked~.widget_switch_label .widget_switch_circle {
left: 50px;
}
.widget_switch_circle {
position: absolute;
display: inline-block;
height: 30px;
width: 30px;
border-radius: 50%;
border: 2px solid #333;
background-color: #eee;
left: 0;
/*过渡效果,可考虑不加*/
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
}
.widget_switch_checkbox:checked~.widget_switch_label {
background: lime;
}
希望大家整理成自己的东西,不懂得属性建议百度,加油