本文實例講述了jQuery實現簡單的回到頂部totop功能。分享給大家供大家參考,具體如下:
<!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("<div id='totop'>totop</div>"); //插入了新標簽 ,記得添加樣式! $("#totop").on('click', function() { scroll(0,200); }); } } }); }; //xxx.js文件來執行 $(function(){ toTop(2); }) </script></html>
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery窗口操作技巧總結》、《jQuery常用插件及用法總結》、《jquery中Ajax用法總結》、《jQuery表格(table)操作技巧匯總》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答