You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery修改W3Schools滚动置顶代码实现慢速平滑滚动效果

基于jQuery实现平滑滚动置顶方案

修改核心是使用jQuery内置的animate()方法控制滚动行为,自动处理浏览器兼容,同时支持自定义滚动速度。

前置准备

在页面的<head>标签内,或者</body>结束标签之前引入jQuery依赖:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

代码修改说明

1. HTML部分(可选优化)

可以去掉按钮上的onclick点击事件绑定,改为通过jQuery统一绑定事件,代码更解耦:

<body>
<button id="myBtn" title="Go to top">Top</button>

<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible 
  <strong>when the user starts to scroll the page</strong>.</div>
</body>

2. CSS部分

原有CSS不需要做任何修改,直接复用即可。

3. JS部分(核心修改)

完全替换原有原生JS代码为jQuery实现的逻辑:

// 页面DOM加载完成后执行
$(function() {
  var $myButton = $('#myBtn');
  
  // 监听页面滚动事件,控制按钮显隐
  $(window).scroll(function() {
    if ($(this).scrollTop() > 20) {
      $myButton.fadeIn(); // 若要和原效果完全一致可替换为$myButton.css('display', 'block')
    } else {
      $myButton.fadeOut(); // 若要和原效果完全一致可替换为$myButton.css('display', 'none')
    }
  });

  // 绑定按钮点击事件,实现平滑滚动到顶部
  $myButton.click(function() {
    // animate第二个参数为滚动时长,单位为毫秒,数值越大滚动速度越慢
    $('html, body').animate({scrollTop: 0}, 800);
  });
});

速度调整说明

只需要修改animate方法的第二个参数即可调整滚动速度:

  • 500:快速滚动,适合内容较短的页面
  • 800:常规速度,大多数场景适用
  • 1200:慢速滚动,适合长内容页面,用户能清晰看到滚动过程

内容的提问来源于stack exchange,提问作者user17144244

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:24:07