如何用 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”按鈕時 −

更新於: 08-05-2020

826 次觀看

開啟你的 職業

透過完成課程獲得認證

開始
廣告