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