导航

回到顶部插件

Posted on 2018-05-11 11:52  小飞博客  阅读(176)  评论(0编辑  收藏  举报
 1 <script src="jquery-1.11.3.min.js"></script>
 2 <script>
 3 (function($){
 4     function Obj(element,options){
 5         this.element = element;
 6         this.defaults = {
 7             time:30,
 8             speed:8,
 9             scrollTop:100
10         };
11         this.options = $.extend({},this.defaults,options)
12      }
13      Obj.prototype.toTop = function(){
14           var options = $.extend({},this.defaults,options);
15           var timer = null;
16           $("body").append($("<span id='toTop' style='position: fixed;width: 54px;height: 54px;bottom: 50px;right: 70px;cursor: pointer;background: red; z-Index: 101;display:none'></span>"));
17           $("#toTop").bind("click",function(){ 
18                clearInterval(timer);
19                timer = setInterval(function(){
20                  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
21                  var iSpeed = Math.floor(0-scrollTop/options.speed);
22                  document.documentElement.scrollTop = document.body.scrollTop = scrollTop + iSpeed;
23                  if(scrollTop == 0){
24                     clearInterval(timer);
25                   } 
26                     },options.time);
27                });
28           return this;
29      };
30      Obj.prototype.scroll = function(){
31          var options = $.extend({},this.defaults,options);
32          this.element.bind("scroll",function(){
33              var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
34              if(scrollTop>=options.scrollTop){
35                   $("#toTop").fadeIn(); 
36               }else{
37                   $("#toTop").fadeOut();
38               }
39          })
40          return this;
41      }
42     $.prototype.extend({
43          "toTop":function(options){
44             var toTop = new Obj(this,options);
45             return toTop.toTop()
46          },
47          "scroll":function(options){
48             var scroll = new Obj(this,options);
49             return scroll.scroll()
50          }
51     })
52 })(jQuery)
53 
54 $(function(){
55   $("#toTop").toTop({
56      time:30,
57      speed:8
58   });
59   $(window).scroll({
60     scrollTop:100
61   });
62 })
63 </script>