如何在 JavaScript 中在按鈕單擊時隱藏 div?
假設以下是我們 div −
<div id="showOrHide"> Welcome in JavaScript </div>
以下是我們的按鈕。單擊後,上面的 div 應該隱藏 −
<button onclick="showOrHideDiv()">Click The Button</button>
在 JavaScript 中使用 style.display 概念來隱藏 div。以下是程式碼 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <button onclick="showOrHideDiv()">Click The Button</button> <div id="showOrHide"> Welcome in JavaScript </div> <script> function showOrHideDiv() { var v = document.getElementById("showOrHide"); if (v.style.display === "none") { v.style.display = "block"; } else { v.style.display = "none"; } } </script> </body> </html>
要執行上述程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
這將產生以下輸出 −
當用戶單擊按鈕時,div 隱藏。螢幕截圖如下 −
廣告