jquery 开关
jQuery 开关实现方法
使用 jQuery 实现开关效果通常涉及切换元素的显示/隐藏状态、类名或属性。以下是几种常见实现方式:
显示/隐藏切换
$('#toggleButton').click(function() {
$('#targetElement').toggle();
});
类名切换(如暗黑模式)

$('#themeSwitch').click(function() {
$('body').toggleClass('dark-mode');
});
属性切换(如复选框样式)
$('.custom-switch').click(function() {
$(this).toggleClass('active');
var isActive = $(this).hasClass('active');
$(this).attr('aria-checked', isActive);
});
滑动切换效果
通过滑动动画实现更平滑的开关效果:

$('#slideToggleBtn').click(function() {
$('#content').slideToggle(300);
});
自定义开关组件
创建带样式的开关控件:
<div class="switch-container">
<input type="checkbox" id="customSwitch" class="switch-input">
<label for="customSwitch" class="switch-label"></label>
</div>
$('.switch-input').change(function() {
if($(this).is(':checked')) {
// 开启状态逻辑
} else {
// 关闭状态逻辑
}
});
状态保存
使用 localStorage 保存开关状态:
$('#saveStateSwitch').change(function() {
localStorage.setItem('switchState', $(this).is(':checked'));
});
// 页面加载时恢复状态
var savedState = localStorage.getItem('switchState') === 'true';
$('#saveStateSwitch').prop('checked', savedState);
以上方法可根据具体需求组合使用,通过 CSS 配合可以实现各种视觉风格的开关效果。






