<!doctype html> <html> <head> <meta charset="utf-8"> <title>回到顶部</title> <style type="text/css"> body{ width: 100%; height: 10000px; } #totop{ width: 50px; height: 50px; line-height: 50px; background: magenta; font-size: 20px; position: fixed; right: 50px; bottom: 50px; } </style> </head> <body> </body> <script src="js/jquery-1.8.3.min.js" ></script> <script> //写在common.js文件中用来调用即可 //1获取滚动条当前的位置 function getscrolltop() { var scrolltop = 0; if (document.documentelement && document.documentelement.scrolltop) { scrolltop = document.documentelement.scrolltop; } else if (document.body) { scrolltop = document.body.scrolltop; } return scrolltop; }; //2获取文档完整的高度 function getscrollheight() { return math.max(document.body.scrollheight, document.documentelement.scrollheight); }; //3回到顶部 function totop(n) { $(window).on('scroll', function() { //console.log(getscrolltop()+!+getscrollheight()); if ($(#totop).size() > 0) { if (getscrolltop() < $(window).height() * n) { $("#totop").remove(); } } else { if (getscrolltop() >= $(window).height() * n) { $(body).after(<p id='totop'>totop</p>); //插入了新标签 ,记得添加样式! $(#totop).on('click', function() { scroll(0,200); }); } } }); }; //xxx.js文件来执行 $(function(){ totop(2); }) </script> </html>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是jquery实现回到顶部功能的详细内容。
