如何用 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; } .hiddenDiv { width: 100%; padding: 20px; text-align: center; background-color: lightblue; margin-top: 20px; display: none; font-size: 20px; } .showBtn { border: none; padding: 15px; font-size: 18px; background-color: rgb(86, 25, 155); color: white; } </style> </head> <body> <h1>Find hidden element using JavaScript</h1> <h2>Click on the below button to display hidden element</h2> <button class="showBtn">Show element</button> <div class="hiddenDiv"> This is a DIV element </div> <script> document.querySelector(".showBtn").addEventListener("click", showHidden); function showHidden() { var x = document.querySelector(".hiddenDiv"); if (window.getComputedStyle(x).display === "none") { x.style.display = "block"; } } </script> </body> </html>
输出
上面的代码将产生以下输出 −
点击“显示元素”按钮 −
广告