Online DEMO: Portal
HTML code (place it anywhere on the page and beautify it with CSS):
JS code:
<script type="text/javascript" src="js/jquery-1.7.2.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { //首先将#back-to-top隐藏 $("#back-to-top").hide(); //当滚动条的位置处于距顶部100像素以下时,跳转链接出现,否则消失 $(function() { $(window).scroll(function() { if ($(window).scrollTop() > 100) { $("#back-to-top").fadeIn(1500); } else { $("#back-to-top").fadeOut(1500); } }); //当点击跳转链接后,回到页面顶部位置 $("#back-to-top").click(function() { $('body,html').animate({ scrollTop: 0 }, 1000); return false; }); }); }); </script>
Here’s a simpler code to return to the top:
Look at the demo first: http://demo.jb51.net/js/2016/gotop/
Full code:
<!DOCTYPE html> <html> <head> <title>基于jquery的返回顶部效果</title> <script type="text/javascript" src="http://img.jb51.net/jslib/jquery/jquery.min.js"></script> <style type="text/css"> #goTop{position:absolute;display:none;width:50px;height:48px;background:#fff url(http://files.jb51.net/file_images/article/201601/gotop.png) no-repeat 16px 15px;border:solid 1px #f9f9f8;border-radius:6px;box-shadow:0 1px 1px rgba(0, 0, 0, 0.2);cursor:pointer} #goTop:hover{height:50px;background-position:16px 16px;box-shadow:0 1px 1px rgba(0, 0, 0, 0.3)} </style> </head> <body> <div style="height:2000px; text-align:center; padding-top:300px">想看到效果就需要拖动滚动条到下面,靠右下角的位置就可以看到</div> <div id="goTop" class="goTop"></div> <script type="text/javascript"> $(window).scroll(function(){ var sc=$(window).scrollTop(); var rwidth=$(window).width()+$(document).scrollLeft(); var rheight=$(window).height()+$(document).scrollTop(); if(sc>0){ $("#goTop").css("display","block"); $("#goTop").css("left",(rwidth-80)+"px"); $("#goTop").css("top",(rheight-120)+"px"); }else{ $("#goTop").css("display","none"); } }); $("#goTop").click(function(){ $('body,html').animate({scrollTop:0},300); }); </script> </body> </html>