如何用 JavaScript 切换隐藏和显示元素?
用 JavaScript 在隐藏和显示元素之间切换,代码如下 −
示例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } button { padding: 10px; border: none; background-color: rgb(51, 51, 192); color: white; font-size: 18px; } .div-visible { width: 100%; padding: 50px 0; text-align: center; background-color: rgb(210, 230, 173); margin-top: 20px; font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Toggle hide and show example</h1> <button class="toggleDisplay">Hide Div</button> <h2>Click on the above button to hide the div below</h2> <div class="div-visible"> This is a div element </div> <script> document .querySelector(".toggleDisplay") .addEventListener("click", toggleDivDisplay); function toggleDivDisplay() { var x = document.querySelector(".div-visible"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </body> </html>
输出
以上代码将产生以下输出 −
在单击“隐藏 Div”按钮时 −
广告