首先,项目中需要做一个开关的按钮,就将复选框和label标签,组合,搞了一个开关,具体效果如下图所示:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
label{
display: inline-block;
width: 50px; height: 22px; background:#dc3545; border-radius: 30px ; transition: background-color .6s linear;
}
/*在标签的前面插入一小圆形*/
label::after{
content: "×";width: 17px; height: 17px; background-color:#FFFFFF;color:#dc3545;display: inline-block;text-align: center;line-height: 17px;position: relative;left:3px;
transition: transform.6s linear; border-radius: 50%;
}
/*获得复选框后面的第一个兄弟元素label*/
input[type=checkbox]:checked+label{
background-color:#28a745;
}
input[type=checkbox]:checked+label::after{
content: "√";color:#28a745;transform: translate(27px);/*向右移动27px*/
}
</style>
</head>
<body>
<div>
<input type="checkbox" id="chk">
<label for="chk"></label>
</div>
</body>
</html>
但是,又遇到一个问题,那就是我需要显示的是在表格的每一行显示,但是一个页面只能由一个id,所以这就需要js控制一下了,效果如下图所示:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<style type="text/css">
body>div{height: 40px;}
label{
display: inline-block;
width: 50px; height: 22px; background:#dc3545; border-radius: 30px ; transition: background-color .6s linear;
}
/*在标签的前面插入一小圆形*/
label::after{
content: "×";width: 17px; height: 17px; background-color:#FFFFFF;color:#dc3545;display: inline-block;text-align: center;line-height: 17px;position: relative;left:3px;
transition: transform.6s linear; border-radius: 50%;
}
/*获得复选框后面的第一个兄弟元素label*/
input[type=checkbox]:checked+label{
background-color:#28a745;
}
input[type=checkbox]:checked+label::after{
content: "√";color:#28a745;transform: translate(27px);/*向右移动27px*/
}
</style>
</head>
<body>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
<div>
<input type="checkbox">
<label class="label"></label>
</div>
</body>
<script type="text/javascript">
var label = $(".label");
for (var i =0;i<label.length;i++) {
label[i].onclick = function(event){
var tdChilds = event.target.parentNode.childNodes;
console.log('tdChilds',tdChilds);
console.log('e',tdChilds[1].checked)
if (tdChilds[1].checked == true) {//当前开关是开的状态
// console.log("选中");
tdChilds[1].checked = false;//关闭开关
} else {
// console.log("没有选中");
tdChilds[1].checked = true;//打开开关
}
}
}
</script>
</html>