Home >Web Front-end >Front-end Q&A >How to implement click-to-hide display in css
CSS Click to Hide Show
In today’s Internet era, the focus of web design has shifted from simple static display to a more advanced interactive experience. Among them, hiding and showing is one of the most commonly used interaction methods. This method allows users to obtain the required information more conveniently and can greatly reduce redundant content on the page. In CSS, there are several methods to hide and show, and this article will introduce them one by one.
The value of the display attribute in CSS controls whether the element is displayed or hidden. Values include:
Using the display attribute, we can hide and display by adding or removing the display attribute of the element. The sample code is as follows:
HTML code:
<div class="box"> <p>隐藏的内容</p> </div> <button id="toggle">显示/隐藏</button>
CSS Code:
.box { display: none; }
JavaScript code:
document.getElementById("toggle").addEventListener("click", function() { var box = document.querySelector(".box"); if(box.style.display === "none") { box.style.display = "block"; } else { box.style.display = "none"; } });
The opacity attribute controls the transparency of the element to achieve the effect of hiding or showing. When the opacity property is set to 0, the element will be completely transparent, so it cannot be seen. When the opacity property is 1, it is fully visible. But it will still take up its space on the page.
HTML code:
<div class="box"> <p>隐藏的内容</p> </div> <button id="toggle">显示/隐藏</button>
CSS code:
.box { opacity: 0; transition: opacity 0.5s ease-in-out; pointer-events: none; } .box.show { opacity: 1; pointer-events: auto; }
JavaScript code:
document.getElementById("toggle").addEventListener("click", function() { var box = document.querySelector(".box"); box.classList.toggle("show"); });
<div class="box"> <p>隐藏的内容</p> </div> <button id="toggle">显示/隐藏</button>CSS code:
.box { visibility: hidden; } .box.show { visibility: visible; }JavaScript code:
document.getElementById("toggle").addEventListener("click", function() { var box = document.querySelector(".box"); box.classList.toggle("show"); });To sum up, whether it is display, opacity or visibility attributes, They can both hide and show. Each of these three methods has its own advantages and disadvantages, and we can choose the appropriate method according to actual needs.
The above is the detailed content of How to implement click-to-hide display in css. For more information, please follow other related articles on the PHP Chinese website!