繁体   English   中英

如何更改切换按钮的背景颜色

[英]How to change background color of toggle button

这是我的代码

<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>

当切换按钮为“ON”时,我想将背景颜色更改为蓝色,将文本更改为白色,将切换按钮为“关闭”时将背景颜色更改为白色,将文本颜色更改为黑色

我使用: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>

不要直接更改内联样式最好的解决方案是为ON & OFF状态和切换类创建css

 $(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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM