1 回答
TA贡献1825条经验 获得超6个赞
如果你从 CSS 开始,也可以用 CSS 完成一切)
简化示例:
label {
display: inline-block;
cursor: pointer;
background: orange;
padding: 5px;
margin: 30px;
}
.onoffswitch-inner::after {
content: "DISAPPROVED";
}
.onoffswitch-inner::before {
content: "APPROVED";
display: none;
}
#onoff:checked ~ .switch-status .onoffswitch-inner::after {
display: none;
}
#onoff:checked ~ .switch-status .onoffswitch-inner::before {
display: inline-block;
}
<input type="checkbox" id="onoff">
<div class="switch-status">
<div>STATUS: <span class="onoffswitch-inner"></span></div>
<div>
<label for="onoff">
<span class="onoffswitch-inner"></span>
</label>
</div>
</div>
但 CSS 强烈依赖于你的标记。
另一种方式,仅使用 JavaScript:
let onoff = document.getElementById('onoff'); // checkbox id
let toggle = document.querySelectorAll('.toggle-txt');
onoff.addEventListener('change', function() {
// run function each time when checkbox is changing
// this == the element, which run the function (here == checkbox)
this.closest('.main-switch').classList.toggle('on');
// find the closest parent with class '.main-switch'
for (let i = 0; i < toggle.length; i++) {
toggle[i].textContent = (this.checked) ? "APPROVED" : "DISAPPROVED";
}
// Google → Ternary operator.
// (check the condition) ? (return value if true) : (value if false)
// property 'checkbox.checked' always contains "true" or "false"
//
});
label {
display: inline-block;
cursor: pointer;
background: orange;
padding: 5px;
margin: 30px;
user-select: none;
}
.main-switch {
/* default switch */
}
.main-switch.on {
background-color: #045acf;
/* some CSS magic only for switching effect */
}
<div>STATUS: <span class="toggle-txt">DISAPPROVED</span></div>
<div>
<label class="main-switch" for="onoff">
<input type="checkbox" id="onoff">
<span class="onoffswitch-inner toggle-txt">DISAPPROVED</span>
</label>
</div>
添加回答
举报