简体   繁体   中英

How to add css of a div when checkbox checked?

The Code:

 #menu-open:checked ~ .logoib { -webkit-filter: invert(100%); filter: invert(100%); } 
 <div id="logo" class="logoib"></div> <input type="checkbox" id="menu-open"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> 

I want to add some CSS of #logo when the checkbox of menu is checked.

css cant affect anything before it, it can only affect stuff after the targeted element change like below

 #menu-open + #logo { color: #ccc; font-style: italic; } #menu-open:checked + #logo { color: #f00; font-style: normal; } 
 <input type="checkbox" id="menu-open"> <div id="logo" class="logoib"> my logo here </div> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> 

You could use pure JS, JQuery or CSS.

Here is a pure JS solution. If you want to set it also on load, you could call myFunction when the DOM is ready.

 function myFunction() { var cb = document.getElementById('menu-open'); var logo = document.getElementById('logo'); if (cb.checked) { logo.setAttribute("class", "newClass"); } else { logo.removeAttribute("class"); } } 
 #menu-open:checked~.logoib { -webkit-filter: invert(100%); filter: invert(100%); } .newClass { color: red; } 
 <div id="logo" class="logoib">Logo </div> <input type="checkbox" id="menu-open" onchange="myFunction()"> <nav class="menu-list"> <a href="#" class="firsta">Home</a> <a href="#">My Works</a> <a href="#">Contact</a> </nav> <label for="menu-open" class="modmenu logoib"> <span></span> </label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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