scrollto.js
// 定义模块
define(['jquery'], function($){
// 构造函数(方法名跟文件名相同,首字母要大些)
function ScrollTo(opts){
// 将用户传递的参数覆盖原来的ScrollTo.DEFAULTS,以"{}"形式返回
this.opts = $.extend({}, ScrollTo.DEFAULTS, opts);
this.$el = $('html, body');
}
// 在原型添加方法move
ScrollTo.prototype.move = function(){
var opts = this.opts,
dest = opts.dest;
if($(window).scrollTop() != dest){
if(!this.$el.is(':animated')){
console.log('log', 1);
this.$el.animate({
scrollTop: dest
}, opts.speed);
}
}
};
// 在原型添加方法go
ScrollTo.prototype.go = function(){
var dest = this.opts.dest;
if($(window).scrollTop != dest){
this.$el.scrollTop(dest);
}
};
// 定义默认值
ScrollTo.DEFAULTS = {
dest: 0,
speed: 800
};
return {
// 返回对象
ScrollTo: ScrollTo
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
backtop.js
// 定义模块
define(['jquery', 'scrollto'], function($, scrollto){
// 构造函数
function BackTop(el, opts){
this.opts = $.extend({}, BackTop.DEFAULTS, opts);
this.el = $(el);
//实例化scrollto
this.scroll = new scrollto.ScrollTo({
dest: 0,
speed: this.opts.speed
});
this._checkPosition();
if(this.opts.mode == 'move'){
// $.proxy(this._move, this)是将this对象替换
// 如果是this.el.on('click', this._move);
// 那么_move方法中的this指的是$('#backTop')
// 替换后this就是BackTop对象。
this.el.on('click', $.proxy(this._move, this));
}else
{
this.el.on('click', $.proxy(this._go, this));
}
$(window).on('scroll', $.proxy(this._checkPosition, this));
}
BackTop.DEFAULTS = {
mode: 'move',
pos: $(window).height(),
speed: 800
};
BackTop.prototype._move = function(){
this.scroll.move();
};
BackTop.prototype._go = function(){
this.scroll.go();
};
BackTop.prototype._checkPosition = function(){
var el = this.el;
//console.log('log:',this);
if($(window).scrollTop() > this.opts.pos){
el.fadeIn();
}else
{
el.fadeOut();
}
};
// 注册jquery插件
$.fn.extend({
backtop: function(opts){
return this.each(function(){
new BackTop(this, opts);
});
}
});
return {
BackTop:BackTop
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
main.js
require.config({
paths: {
jquery: 'jquery.min',
}
});
requirejs(['jquery', 'backtop'], function($, backtop) {
$('#backTop').backtop({
mode: 'move'
});
});