如何用 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>
輸出
上面的程式碼將產生以下輸出 −
點選“顯示元素”按鈕 −
廣告