jQuery slideUp() 方法



jQuery 中的 slideUp() 方法用於透過逐漸將選定元素的高度減小到零來向上滑動(或隱藏)選定元素。它會建立一個向上滑動的動畫,使元素從 DOM 中消失。

此效果主要用於建立下拉選單或在單擊元素後將其從 DOM 中隱藏等場景。

要向下滑動(或顯示)選定元素,我們需要使用 slideDown() 方法。

語法

以下是 jQuery slideUp() 方法的語法:

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

引數

此方法接受以下引數:

  • speed(可選):一個字串或數字,用於確定動畫執行多長時間。預設值為 400 毫秒。可能的值為:毫秒、slow、fast。

  • easing(可選):一個字串,指示要用於過渡的緩動函式。預設值為 "swing"。可能的值為:swing、linear。

  • callback(可選):動畫完成後要執行的函式。

示例 1

在此示例中,我們對 ID 為 "box" 的 <div> 元素使用 slideUp() 方法,使其逐漸向上滑動並消失:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#slideUpButton").click(function(){
    $("#box").slideUp();
  });
});
</script>
</head>
<body>

<div id="box" style="width: 200px; height: 200px; background-color: lightblue;">
  <p>This is a box.</p>
</div>
<button id="slideUpButton">Slide Up</button>
</body>
</html>

當我們單擊按鈕時,它會觸發 slideUp(),<div> 會逐漸向上滑動並隱藏。

示例 2

在以下示例中,我們使用自定義速度 (5000;即 5 秒) 的 slideUp() 方法:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#slideUpButton").click(function(){
    $("#box").slideUp(5000); // Slide up over 5 seconds
  });
});
</script>
</head>
<body>
<div id="box" style="width: 200px; height: 200px; background-color: lightblue;">
  <p>This is a box.</p>
</div>
<button id="slideUpButton">Slide Up</button>
</body>
</html>

當我們單擊“向上滑動”按鈕時,它會觸發 ID 為 "box" 的 <div> 元素上的 slideUp() 方法,動畫需要 5 秒才能完成。

示例 3

在此示例中,我們已將回調函式作為第二個引數提供給 slideUp() 方法:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("#slideUpButton").click(function(){
    $("#box").slideUp(1000, function(){
      alert("The box has slid up!");
    });
  });
});
</script>
</head>
<body>

<div id="box" style="width: 200px; height: 200px; background-color: lightblue;">
  <p>This is a box.</p>
</div>
<button id="slideUpButton">Slide Up</button>
</body>
</html>

動畫完成後將執行回撥函式,並顯示一條警報訊息,提示“盒子已向上滑動!”。

jquery_ref_effects.htm
廣告

© . All rights reserved.