jQuery 中的動畫滾動

  1. 在 jQuery 中使用 animate() 方法來滾動
  2. 在 jQuery 中使用 animate() 方法與時間繫結來滾動頁面
jQuery 中的動畫滾動

jQuery 因其簡單的語法來完成複雜的想法而被廣泛推廣,而 JavaScript ES6 是當今的強敵。

當我們專注於將 div 或網頁滾動到某個高度時,我們會注意到幾種解決方案。然而,jQuery animate() 方法明確地接受 bodyhtml 的例項並將滾動作為首選項。

我們將通過 jQuery animate() 方法在示例集中執行基本的垂直滾動。在後一個示例中,我們將檢查一個具有有限時間範圍的例項。

在 jQuery 中使用 animate() 方法來滾動

在這方面,我們將接受 bodyhtml 元素的例項。因此,該約定使得多個瀏覽器可以執行該函式,而不管它們的約束如何。

接下來,我們將與例項一起啟動 animate() 方法並設定規範 scrollTop: "0"。我們還可以將 scrollTop 設定為任何偏好值。

在這種情況下,頁面不會路由到頂部;相反,它將爬升到整個頁面高度和 scrollTop 值之間的距離。

程式碼片段:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<h4>TOP</h4>
<h4>TOP-20</h4>
<div id="pos" style="height: 600px;background:pink"></div><br>
<button onclick="press()">Go to Top</button>
<script>
function press(){
  $("html, body").animate({scrollTop: "20"});
}
</script>

輸出:

使用 animate 方法來滾動

在 jQuery 中使用 animate() 方法與時間繫結來滾動頁面

此示例包含與前一個類似的功能。但是這裡的補充是我們可以在不定義 setInterval 函式的情況下設定滾動的時間。

我們要做的就是新增優選的時間以及 scrollTop 屬性。這將緩解或確保頁面滾動的速度值。

程式碼片段:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<h4>TOP</h4>
<div id="pos" style="height: 600px;background:powderblue"></div><br>
<button onclick="press()">Go to Top</button>
<script>
function press(){
  $("html, body").animate({scrollTop: "0"}, 3000);
}
</script>

輸出:

使用帶時間限制的動畫方法滾動頁面

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

相關文章 - jQuery Scroll