forked from duncanmcdougall/jQuery-Background-Cover
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.backgroundcover.js
78 lines (66 loc) · 2.44 KB
/
jquery.backgroundcover.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
/*!
* jquery.backgroundcover.js
* https://github.com/duncanmcdougall/jQuery-Background-Cover
* Copyright 2013 Duncan McDougall and other contributors; Licensed MIT
*/
;(function ($) {
'use strict';
$.fn.backgroundCover = function () {
var plugin = this;
var cover = function() {
$(plugin).each(function (idx, item) {
var imageContainer = $(item).parent();
$(item).css({ 'position': 'absolute', 'max-width': 'none', 'display': 'block' });
if ($(item).parents().length < 3) {
$(item).css("zIndex", "-1");
}
imageContainer.css({ 'position': 'relative', 'overflow': 'hidden' });
var cW = imageContainer.outerWidth();
var cH = imageContainer.outerHeight();
var iW = $(item).attr("width");
var iH = $(item).attr("height");
// If image is to narrow scale to match container width
if (iW < cW) {
var ratio = cW / iW;
iW = cW;
iH = iH * ratio;
}
// If image is too short scale to match container height
if (iH < cH) {
var ratio = cH / iH;
iH = cH;
iW = iW * ratio;
}
// If image is bigger in both dimensions scale down to match an edge
if (iW > cW && iH > cH) {
var widthRatio = cW / iW;
var heightRatio = cH / iH;
if (widthRatio > heightRatio) {
iW = cW;
iH = iH * widthRatio;
} else {
iH = cH;
iW = iW * heightRatio;
}
}
$(item).width(iW).height(iH);
if (iH > cH) {
var shift = (iH - cH) / 2;
$(item).css('top', -shift);
} else {
$(item).css('top', '');
}
if (iW > cW) {
var shift = (iW - cW) / 2;
$(item).css('left', -shift);
} else {
$(item).css('left', '');
}
});
}
cover();
$(window).resize(function () {
cover();
});
}
})(jQuery);