[英]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.