帮我写一个基于jq的switch开关
时间: 2023-08-28 12:16:22 浏览: 169
好的,以下是一个基于jq的switch开关的示例代码:
HTML代码:
```
<div class="switch-wrap">
<input type="checkbox" id="switch" class="switch" />
<label for="switch" class="switch-label"></label>
</div>
```
CSS代码:
```
.switch-wrap {
position: relative;
display: inline-block;
width: 50px;
height: 30px;
margin: 10px;
}
.switch {
display: none;
}
.switch-label {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 30px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.switch-label:before {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 26px;
height: 26px;
background-color: #fff;
border-radius: 50%;
transition: transform 0.3s ease;
}
.switch:checked + .switch-label {
background-color: #2ecc71;
}
.switch:checked + .switch-label:before {
transform: translateX(20px);
}
```
jQuery代码:
```
$(document).ready(function() {
$('.switch').on('change', function() {
if ($(this).is(':checked')) {
// 开关打开时的操作
console.log('开关已打开');
} else {
// 开关关闭时的操作
console.log('开关已关闭');
}
});
});
```
当用户点击switch开关时,会触发change事件,根据开关的checked属性值来执行相应操作。CSS中定义了开关的样式,包括开关的背景色、圆形按钮的样式等。
阅读全文