jquery实现点击页面回到顶部 发布时间:2024/02/19 1.首先,需要引入jquery库文件,可以使用cdn或者下载本地文件进行引入。在html文档中增加以下代码: <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script> 复制代码 2.增加回到顶部的按钮。在html文档中放置一个按钮,并设置id为"back-to-top",并设置样式。 <button id="back-to-top" style="display: none; position: fixed; bottom: 30px; right: 30px; z-index: 999;"> 回到顶部 </button> 复制代码 3.实现jquery回到顶部效果。在js文件中增加以下代码: $(document).ready(function() { //文档加载后执行以下操作 $(window).scroll(function() { //当窗口滚动时执行以下操作 if ($(this).scrollTop() > 100) { //当滚动高度超过100时,显示回到顶部按钮 $('#back-to-top').fadeIn(); } else { //否则隐藏 $('#back-to-top').fadeOut(); } }); $('#back-to-top').click(function() { //当点击回到顶部按钮时执行以下操作 $('html, body').animate({scrollTop : 0},800); //动画效果,在800ms内平滑滚动到顶部 return false; }); }); 复制代码 4.实现成功后,页面中滚动时,滚动高度超过100时,回到顶部按钮会以动画效果渐显出来,点击按钮后会以平滑动画回到页面顶部。 示例一: CodePen 示例二: <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>回到顶部示例</title> <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script> </head> <body> <button id="back-to-top" style="display: none; position: fixed; bottom: 30px; right: 30px; z-index: 999;">回到顶部</button> <div style="height: 2000px; background-color: #eee; text-align: center;"> <h1>滚动一下,看看回到顶部按钮的效果吧</h1> </div> <script> $(document).ready(function() { $(window).scroll(function(){ if ($(this).scrollTop() > 100) { $('#back-to-top').fadeIn(); } else { $('#back-to-top').fadeOut(); } }); $('#back-to-top').click(function(){ $('html, body').animate({scrollTop : 0},800); return false; }); }); </script> </body> </html> 复制代码