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

本文实例讲述了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的程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。