简体   繁体   English

HTML:选中复选框后,元素不可见

[英]HTML: Turn Element invisible when checkbox is checked

I have a checkbox in the header of my html code and a box in the body. 我的html代码的标题中有一个复选框,正文中有一个框。 I need the box to disappear when the checkbox is checked. 选中复选框时,我需要该框消失。

I will provide the code below but in short I can make the checkbox itself disappear when it is checked but when I add in the class of the element I want to vanish it stops working at all. 我将在下面提供代码,但总之,我可以使复选框本身在被选中时消失,但是当我添加要消失的元素的类时,它完全无法工作。 I have tried a couple different forms of the CSS but nothing has changed it. 我尝试了几种不同形式的CSS,但是没有任何改变。

 #toggle:checked ~ div .sidebar{ display:none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" /> </div> </nav> <div class="sidebar"> </div> 

You have a small typo in your CSS selector #toggle:checked ~ div .sidebar . CSS选择器#toggle:checked ~ div .sidebar有一个小的错字。 There should be no space between div and .sidebar because your goal is to select "the div with class name sidebar " (not "any element with class name sidebar that is a child of a div "). div.sidebar之间应该没有空格,因为您的目标是选择“类名为sidebardiv ”(而不是“类名为sidebardiv的子元素的任何元素”)。

Another issue is that you are incorrectly using the Adjacent Sibling Combinator in your CSS selector. 另一个问题是您在CSS选择器中错误地使用了Adjacent Sibling Combinator In order for your selector to work properly, the div.sidebar should be a child of the same parent as the #toggle element. 为了使您的选择器正常工作, div.sidebar应该是与#toggle元素相同的父#toggle子级。

 #toggle:checked ~ div.sidebar { display: none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" /> <div class="sidebar"></div> </div> </nav> 

Assuming you cannot change your HTML structure, since you are trying to alter a "div" that is not a sibling or a descendent of the checkbox, you will need javascript to do this. 假设您无法更改HTML结构,因为您试图更改不是该复选框的同级或后代的“ div”,则需要使用javascript来做到这一点。

 function handleChange(checkbox) { if (checkbox.checked == true) { document.getElementsByClassName("sidebar")[0].classList.add("hidden");; } else { document.getElementsByClassName("sidebar")[0].classList.remove("hidden");; } } 
 .sidebar.hidden { display: none; } .sidebar { width: 100px; height: 100px; background: #000; } 
 <nav class="navbar"> <div class="container"> <div class="navbar-header"> <label for="toggle" class="sidebar-toggle"></label> </div> <input type="checkbox" id="toggle" onchange='handleChange(this)' /> </div> </nav> <div class="sidebar"> </div> 

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

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