写移动端的时候,引入的zepto.js里的animate不包括scrollTop,因此返回顶部的时候,没有动画的效果。这里我使用的是setInterval的方法。代码详情以下javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>goTop</title> <script src="zepto.min.js" type="text/javascript" ></script> <style type="text/css" media="screen"> *{ margin: 0; padding: 0; } .goTop{ position: fixed; bottom: 20px; right: 20px; width: 100px; height: 50px; border: 1px solid #ccc; text-align: center; line-height: 50px; background: pink; } .hello{ width: 600px; height: 2000px; background: yellow; } </style> </head> <body> <div class="goTop">返回顶部</div> <div class="hello"></div> </body> <script type="text/javascript"> $(function(){ $('.goTop').click(function(){ //获取当前scrollTop的位置 var curScroll = $(document.body).scrollTop(); //上升的位移 var speed = 5; if(curScroll>0){ setInterval(timer,1); } console.log(curScroll); function timer(){ if(curScroll>0){ curScroll = curScroll-speed; $(document.body).scrollTop(curScroll); console.log(curScroll); if(curScroll<=0){ $(document.body).scrollTop(0); clearInterval(timer); console.log("清除计时器") } } } }) }) </script> </html>