一、什麼是slideUp()方法

slideUp()是jQuery中用於向上滑動隱藏元素的動畫方法。它通過逐漸減小元素的高度,使元素"滑動"向上消失,而不是突然消失。

重要提示:slideUp()方法隱藏的元素不會被完全移除(不再影響頁面佈局),只是高度變小,看起來像是"滑"到上面去了。

二、基本語法

$(selector).slideUp(speed, easing, callback);

參數説明

參數

説明

可選值

speed

滑動效果的速度

"slow", "fast", 或毫秒數(如3000)

easing

動畫速度變化方式

"swing"(默認,開頭結尾慢,中間快), "linear"(勻速)

callback

動畫完成後執行的函數

一個函數

三、實用代碼示例

1. 基本用法:點擊按鈕隱藏段落

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <style>
    div {
      width: 300px;
      height: 100px;
      padding: 20px;
      border: 2px solid green;
      margin: 10px;
    }
  </style>
</head>
<body>
  <div>
    <p>這段文字將滑動隱藏</p>
    <button class="slideUpBtn">點擊隱藏</button>
  </div>

  <script>
    $(document).ready(function() {
      $(".slideUpBtn").click(function() {
        $("p").slideUp(); // 默認速度隱藏
      });
    });
  </script>
</body>
</html>

2. 帶速度參數:指定滑動時間

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <style>
    div {
      width: 300px;
      height: 100px;
      padding: 20px;
      border: 2px solid blue;
      margin: 10px;
    }
  </style>
</head>
<body>
  <div>
    <p>這段文字將快速滑動隱藏</p>
    <button class="slideUpBtn">點擊隱藏(快)</button>
  </div>

  <script>
    $(document).ready(function() {
      $(".slideUpBtn").click(function() {
        $("p").slideUp(1000); // 1000毫秒(1秒)內隱藏
      });
    });
  </script>
</body>
</html>

3. 帶回調函數:隱藏完成後執行操作

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <style>
    div {
      width: 300px;
      height: 100px;
      padding: 20px;
      border: 2px solid red;
      margin: 10px;
    }
  </style>
</head>
<body>
  <div>
    <p>這段文字將滑動隱藏後顯示提示</p>
    <button class="slideUpBtn">點擊隱藏(帶提示)</button>
  </div>

  <script>
    $(document).ready(function() {
      $(".slideUpBtn").click(function() {
        $("p").slideUp("fast", function() {
          alert("元素已隱藏!"); // 隱藏完成後彈出提示
        });
      });
    });
  </script>
</body>
</html>

4. 與slideToggle結合使用:切換顯示隱藏

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <style>
    #panel {
      width: 300px;
      height: 100px;
      padding: 20px;
      border: 2px solid #000;
      background-color: #f0f0f0;
      display: none;
    }
    button {
      padding: 10px 20px;
      margin: 10px;
    }
  </style>
</head>
<body>
  <button id="toggleBtn">點擊切換顯示/隱藏</button>
  <div id="panel">
    <p>這個面板會滑動顯示/隱藏</p>
  </div>

  <script>
    $(document).ready(function() {
      $("#toggleBtn").click(function() {
        $("#panel").slideToggle("slow"); // 切換顯示/隱藏
      });
    });
  </script>
</body>
</html>

四、slideUp()與slideDown()的區別

方法

作用

適用場景

slideUp()

向上滑動隱藏元素

隱藏元素,如關閉面板

slideDown()

向下滑動顯示元素

顯示元素,如打開面板

slideToggle()

切換顯示/隱藏

交互式切換,如導航菜單