-
Notifications
You must be signed in to change notification settings - Fork 5
/
jquery.bgdsize.js
97 lines (81 loc) · 1.95 KB
/
jquery.bgdsize.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* CSS Background-Size jQuery Plugin v.1.0
*
* By Aram Kocharyan, 2012.
* Released under the MIT licence.
* http://aramk.com/
*/
(function($) {
$.bgdSize = function(el, options) {
var base = this;
base.defaults = {
mode : '', // blank will do nothing, use 'cover' or 'contain'
repeatCount : 0,
repeatMax : 10,
repeatFreq : 100
};
base.$el = $(el);
base.el = el;
base.init = function() {
if (typeof options == 'string') {
base.options = $.extend(base.defaults, {
mode : options
});
} else {
base.options = $.extend(base.defaults, options);
}
base.repeat();
};
base.repeat = function() {
base.options.repeatCount++;
if (base.options.repeatCount > base.options.repeatMax) {
return;
}
base.scale();
if (base.done == false) {
base.done = true;
setTimeout(function() {
base.repeat();
}, base.options.repeatFreq);
}
};
base.scale = function() {
var mode;
if (base.options.mode == 'cover') {
mode = Math.max;
} else if (base.options.mode == 'contain') {
mode = Math.min;
} else {
return;
}
var parent = base.$el.parent();
if (!parent) {
return;
}
parent.css('overflow', 'hidden');
var width = base.$el.width();
var height = base.$el.height();
if (width == 0 || height == 0) {
base.done = false;
return;
}
var parentWidth = parent.width();
var parentHeight = parent.height();
var widthRatio = parentWidth / width;
var heightRatio = parentHeight / height;
var ratio = mode(widthRatio, heightRatio);
var newWidth = ratio * width;
var newHeight = ratio * height;
base.$el.width(newWidth);
base.$el.height(newHeight);
base.$el.css('margin-left', (parentWidth - newWidth) / 2);
base.$el.css('margin-top', (parentHeight - newHeight) / 2);
};
base.init();
};
$.fn.bgdSize = function(options) {
return this.each(function() {
(new $.bgdSize(this, options));
});
};
})(jQuery);