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

网络编程 2021-07-04 17:32www.168986.cn编程入门
这篇文章主要介绍了requireJS模块化实现返回顶部功能的方法,结合实例形式详细分析了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="" class="btn"></div>
</body>
</html>

新建main.js

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

创建back模块 back.js

/**
 * Created by Administrator on 2016/3/24.
 */
define(["jquery","scrollTo"],function($, scroll){
  function back(el,opts){
    this.opts = $.extend({},back.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))
  };
  back.prototype._move = function(){
    this.scroll.move()
  };
  back.prototype._go = function(){
    this.scroll.go()
  };
  back.prototype._checkPostion = function(){
    if($(window).scrollTop() > this.opts.pos){
      this.$el.fadeIn();
    }else{
      this.$el.fadeOut();
    }
  }
  $.fn.extend({
    back:function(opts){
      return this.each(function(){
        new back(this,opts);
      })
    }
  });
  back.default = {
    mode:"move",
    pos:100,
    dest:0,
    speed:800
  }
  return{
    back:back
  }
})

back 依赖 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);
      / 

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by