当前位置: 移动技术网 > IT编程>开发语言>JavaScript > requireJS模块化实现返回顶部功能的方法详解

requireJS模块化实现返回顶部功能的方法详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了requirejs模块化实现返回顶部功能的方法。分享给大家供大家参考,具体如下:

引用requirejs

<script src="require.js" data-main="main"></script>

html部分

<!doctype html>
<html>
<head lang="en">
  <meta charset="utf-8">
  <title></title>
  <style>
    body{padding: 0; margin: 0; height: 3000px}
    .btn{width: 80px; height: 80px;
      position: fixed; bottom: 0; left: 50%; background: #ddd}
  </style>
  <script src="require.js" data-main="main"></script>
</head>
<body>
  <div id="top" class="btn"></div>
</body>
</html>

新建main.js

require.config({
  paths:{
    jquery:'jquery'
  }
});
requirejs(['jquery','backtop'],function($,backtop){
  $('#top').backtop({
    mode:"move",
    pos:100,
    dest:500,
    speed:20000
  })
});

创建backtop模块 backtop.js

/**
 * created by administrator on 2016/3/24.
 */
define(["jquery","scrollto"],function($, scroll){
  function backtop(el,opts){
    this.opts = $.extend({},backtop.default,opts);
    this.$el = $(el);
    this.scroll = new scroll.scrollto({
      dest:this.opts.dest,
      speed:this.opts.speed
    });
    this._checkpostion();
    if(this.opts.mode == "move"){
      this.$el.on("click", $.proxy(this._move,this))
    }else{
      this.$el.on("click", $.proxy(this._go,this))
    }
    $(window).on("scroll", $.proxy(this._checkpostion,this))
  };
  backtop.prototype._move = function(){
    this.scroll.move()
  };
  backtop.prototype._go = function(){
    this.scroll.go()
  };
  backtop.prototype._checkpostion = function(){
    if($(window).scrolltop() > this.opts.pos){
      this.$el.fadein();
    }else{
      this.$el.fadeout();
    }
  }
  $.fn.extend({
    backtop:function(opts){
      return this.each(function(){
        new backtop(this,opts);
      })
    }
  });
  backtop.default = {
    mode:"move",
    pos:100,
    dest:0,
    speed:800
  }
  return{
    backtop:backtop
  }
})

backtop 依赖 scrollto模块

创建scrollto.js

define(['jquery'],function($){
  function scrollto(opts){
    this.opts = $.extend({},scrollto.defaults,opts);
    this.$el = $("html,body");
  }
  scrollto.prototype.move = function(){
    if($(window).scrolltop() != this.opts.dest){
      //if(!this.$el.is(":animated")){
        this.$el.animate({scrolltop:this.opts.dest},this.opts.speed);
      //}
    }
  };
  scrollto.prototype.go = function(){
    this.$el.scrolltop(this.opts.dest)
  };
  scrollto.defaults = {
    dest:0,
    speed:800
  };
  return {
    scrollto:scrollto
  }
});

希望本文所述对大家基于requirejs的程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网