jQuery实现回到顶部功能

在网页中,我们经常会由于网页内容过长,而需要在浏览网页时有一个快速回到网页顶部的功能,在浏览网页内容离顶部

有一段距离时,出现快速回到网页顶部的工具,从而能使我们的网页更人性化。

以下分为几个步骤来实现:

步骤1:引入jquery库

1 <script type="text/javascript" src="js/jquery-1.8.0.js"></script>

步骤2:在网页中引入回到顶部的网页元素,并且设置元素的样式

1 <div id="gotop"></div>

设置元素样式,默认开始隐藏

 1 <style type="text/css">
 2 #gotop{
 3     display:none;
 4     55px;
 5     height:55px;
 6     position:fixed;
 7     right:50px;
 8     bottom:50px;
 9     background:url(images/backtop2013.png) no-repeat -70px 0px;    
10 }
11 </style>

步骤3:定义js来控制元素的渐显、渐隐功能,并且控制网页滚动条的位置。

 1 <script type="text/javascript">
 2 function goTop()
 3 {
 4     $(window).scroll(function(e) {
 5         //若滚动条离顶部大于100元素
 6         if($(window).scrollTop()>100)
 7             $("#gotop").fadeIn(1000);//以1秒的间隔渐显id=gotop的元素
 8         else
 9             $("#gotop").fadeOut(1000);//以1秒的间隔渐隐id=gotop的元素
10     });
11 };
12 $(function(){
13     //点击回到顶部的元素
14     $("#gotop").click(function(e) {
15             //以1秒的间隔返回顶部
16             $('body,html').animate({scrollTop:0},1000);
17     });
18     $("#gotop").mouseover(function(e) {
19         $(this).css("background","url(images/backtop2013.png) no-repeat 0px 0px");
20     });
21     $("#gotop").mouseout(function(e) {
22         $(this).css("background","url(images/backtop2013.png) no-repeat -70px 0px");
23     });
24     goTop();//实现回到顶部元素的渐显与渐隐
25 });
26 </script>

按照上面的3个步骤,将可以实现回到顶部的功能。

这个图片是回到顶部元素用到的背景图片,需要的朋友可以下载它,或者自己设置样式时,使用自定义的图片。



----------------------------------------------------------------------
“我可以接受失败,但绝对不能接受自己未曾奋斗过。”--迈克尔-乔丹
“I can accept failure, but I can't accept not trying.”--Michael Jordan.
原文地址:https://www.cnblogs.com/beyondfengyu/p/2987823.html