這次為大家帶來用requireJS添加返回頂部功能,用requireJS添加返回頂部功能的注意事項有哪些,下面就是實戰案例,一起來看一下。
本文實例講述了requireJS模組化實作傳回頂部功能的方法。分享給大家參考,具體如下:
# 引用requireJs
<script src="require.js" data-main="main"></script>
html部分
<script src="require.js" data-main="main"></script>
新建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 } });
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是用requireJS添加返回頂部功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!