现在的位置: 网页制作教程网站制作教程 >正文
DreamWeaver教程

基于Jquery实现的返回浏览器顶部的效果

发表于2016/12/10 网站制作教程 0条评论 ⁄ 热度 2,172℃

如果网页的高度比较高,往往会需要在页面的侧边加一个返回顶部的按钮。

本文主要介绍基于jquery实现返回顶部的效果,方法如下:

1.引用jquery库文件。

2.设置默认参数(showHeight :设置滚动高度时显示、speed :返回顶部的速度以毫秒为单位)。

$(function() {
  $.fn.manhuatoTop = function(options) {
    var defaults = {
      showHeight : 150,
      speed : 1000
    };
    var options = $.extend(defaults,options);
    $("body").prepend("<div id='totop'><a>返回</a></div>");
    var $toTop = $(this);
    var $top = $("#totop");
    var $ta = $("#totop a");
    $toTop.scroll(function(){
      var scrolltop=$(this).scrollTop();
      if(scrolltop>=options.showHeight){
        $top.show();
      }
      else{
        $top.hide();
      }
    });
    $ta.hover(function(){
      $(this).addClass("cur");
    },function(){
      $(this).removeClass("cur");
    });
    $top.click(function(){
      $("html,body").animate({scrollTop: 0}, options.speed);
    });
  }
});

Css样式表:

*{padding:0; margin:0}
body{height:2000px}
#totop{position:fixed;bottom:40px;right:10px;z-index:999;width:71px; cursor:pointer; display:none;}
*html #totop{position:absolute;cursor:pointer;right:10px; display:none;top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight)-112+"px")}
#totop a{display:block;width:71px;height:24px;padding-top:48px;background:url(/images/toTop.gif) no-repeat;text-align:center;color:#888}
#totop a.cur{background-position:-88px 0;text-decoration:none;color:#3a9}

用到的图片:

返回顶部按钮

使用方法:

<script type="text/javascript">
$(function (){
  $(window).manhuatoTop({
    showHeight : 100,//设置滚动高度时显示
    speed : 500 //返回顶部的速度以毫秒为单位
  });
});
</script>  
  • 暂无评论