jQuery实现返回顶部
jQuery实现返回顶部
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery</title> <style> .back_top{ position: fixed; background:gray; color: #ffffff; padding: 5px; bottom: 30px; right: 30px; width: 42px; text-align: center; cursor: pointer; } </style> </head> <body> <div> <h1>我是顶部</h1> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <div class="back_top">Top</div> </div> <script src="js/jquery-2.1.0.js"></script> <script> //不直接跳转 $(".back_top").click(function(){ $("body,html").scrollTop(0); }) //平滑跳转 $(".back_top").click(function(){ //滚动时 滚动条离上部的距离 var distance = $("html").scrollTop() + $("body").scrollTop(); //设置滚动的总时间 var time=500; //间隔时间 var intervalTime=50; var itemDistance=distance/(time/intervalTime); var intervalId = setInterval(function(){ distance-=itemDistance; if(distance<=0){ clearInterval(intervalId); } $("html,body").scrollTop(distance-itemDistance); },intervalTime); }) </script> </body> </html>