jQuery实现回到顶部功能

在网页中,我们经常会由于网页内容过长,而需要在浏览网页时有一个快速回到网页顶部的功能,在浏览网页内容离顶部有一段距离时,出现快速回到网页顶部的工具,从而能使我们的网页更人性化。

 

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

步骤1引入jquery

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

 

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

<div id="gotop"></div> 设置元素样式,默认开始隐藏

<style type="text/css">

#gotop{

display:none;

55px;

height:55px;

position:fixed;

right:50px;

bottom:50px;

background:url(images/backtop2013.png) no-repeat -70px 0px; 

}

</style>

 

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

 <script type="text/javascript">

 function goTop({

     $(window).scroll(function(e) {

         //若滚动条离顶部大于100元素

         if($(window).scrollTop()>100)

              $("#gotop").fadeIn(1000);//1秒的间隔渐显id=gotop的元素

          else

              $("#gotop").fadeOut(1000);//1秒的间隔渐隐id=gotop的元素

    });

1};

 $(function(){

     //点击回到顶部的元素

     $("#gotop").click(function(e) {

             //1秒的间隔返回顶部

             $('body,html').animate({scrollTop:0},1000);

    });

     $("#gotop").mouseover(function(e) {

         $(this).css("background","url(images/backtop2013.png) no-repeat 0px 0px");

    });

     $("#gotop").mouseout(function(e) {

         $(this).css("background","url(images/backtop2013.png) no-repeat -70px 0px");

    });

     goTop();//实现回到顶部元素的渐显与渐隐

 });

 </script>

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

原文地址:https://www.cnblogs.com/black-stabber/p/3175088.html