1、整体功能概述
此代码实现了在网页中点击 “返回顶部” 按钮,页面以动画效果平滑滚动到顶部的功能。当页面滚动超过一定距离时,“返回顶部” 按钮会显示;而当页面滚动到较接近顶部的位置时,按钮则会隐藏。
2、CSS
#back-to-top { position: fixed; bottom: 20px; right: 10px; background-color: #333; color: white; padding: 10px; cursor: pointer; display: none; } <div id="back-to-top">返回顶部</div>
3、jQuery
$(document).ready(function () { // 当滚动条滚动时,判断是否显示返回顶部按钮 $(window).scroll(function () { if ($(this).scrollTop() > 300) { $('#back-to-top').fadeIn(); } else { $('#back-to-top').fadeOut(); } }); // 点击返回顶部按钮时,页面平滑滚动到顶部 $('#back-to-top').click(function () { $('html, body').animate({ scrollTop: 0 }, 500); return false; }); });
4、代码分析
back-to-top用固定定位fixed;bottom:20px; right:10px;
$(document).ready():此函数确保在文档加载完成后再执行其中的代码。
$(window).scroll():当窗口滚动时触发该函数,依据滚动距离判断是否显示或隐藏返回顶部按钮。若滚动距离scrollTop()超过 300 像素,使用 fadeIn() 方法淡入显示按钮;反之,使用 fadeOut() 方法淡出隐藏按钮。
$('#back-to-top').click():当点击返回顶部按钮时触发该函数,使用 animate() 方法使 html 和 body 元素以 500 毫秒的动画效果滚动到页面顶部。return false; 用于阻止默认行为。
动画效果:使用 animate() 方法实现平滑滚动,增强了用户体验。

