这是我的代码
<label style="margin-top: 2px;margin-right: 13px;" class="toggle"><input type="checkbox"
onclick="updateGroup(this)" name="screen" value="Profile" actionname="Profile">
<i data-swchoff-text="Off" data-swchon-text="On"></i></label>
当切换按钮为“开”时,我想将背景颜色更改为蓝色,将文本更改为白色;当切换按钮为“关”时,我要将背景颜色更改为白色,将文本颜色更改为黑色
答案 0 :(得分:1)
我将:checked
属性和tilde(~)
运算符一起使用,以在切换时设置background & text
的颜色。
.toggle{
position: relative;
display: inline-block;
}
.toggle input{opacity: 0; position: absolute; left: 0; top: 0}
.toggle i{
position: relative;
background: #fff;
color: #000;
height: 34px;
width: 50px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ccc;
border-radius: 4px;
font-style: normal;
transition: 350ms;
font-family: Arial;
}
.toggle input:checked ~ i{
background: blue;
border: 1px solid blue;
color: #fff;
}
.toggle i:before{
content: attr(data-swchoff-text);
}
.toggle input:checked ~ i:before{
content: attr(data-swchon-text);
}
<label class="toggle">
<input type="checkbox" name="screen" value="Profile" actionname="Profile">
<i data-swchoff-text="Off" data-swchon-text="On"></i>
</label>
答案 1 :(得分:0)
不要直接更改内联样式,最佳解决方案正在为 ON 和< strong> OFF 状态并切换类
$(document).ready(function() {
$('input[name=theme]').change(function(e) {
$('#MainContent').toggleClass('light-theme dark-theme');
});
});
.theme {
margin: 15px;
padding: 15px;
}
.theme.dark-theme {
background: blue;
color: white;
}
.theme.light-theme {
background: white;
color: black;
}
<label style="margin-top: 2px;margin-right: 13px;" class="toggle">
<input type="checkbox" name="theme" />
Blue Theme
</label>
<div id="MainContent" class="theme light-theme">
<div id="artical">
<h3>Title here</h3>
More Info More Info More Info More Info More Info More Info <br />
More Info More Info More Info More Info More Info More Info
More Info More Info More Info More Info More Info More Info <br />
More Info More Info More Info More Info More Info More Info
More Info More Info More Info More Info More Info More Info <br />
More Info More Info More Info More Info More Info More Info
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>