-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg.position.js
98 lines (85 loc) · 2.46 KB
/
img.position.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
97
98
;(function($){
'use strict';
$.fn.imgPosition = function(options){
var thisElement = $(this.selector);
var defaults = {
width: thisElement.width(),
height: thisElement.height(),
};
var setting = $.extend(defaults, options);
var addEvent = function(elm,listener,fn){
try {
elm.addEventListener(listener,fn,false);
} catch(e) {
elm.attachEvent("on"+listener,fn);
}
};
addEvent(window,"load",function(){
thisElement.css({
'position': 'relative',
'width' : defaults.width,
'height' : defaults.height
});
thisElement.find("img").each(function(){
var newImg = new Image();
newImg.src = $(this).attr("src");
var reference = resize(newImg);
$(this)
.attr({
"width": reference.width,
"height": reference.height,
})
.css({
"position": "absolute",
"top": "50%",
"left": "50%",
"margin-top": reference.marginTop,
"margin-left": reference.marginLeft
});
});
});
var getNewSise = function(imgWidth, imgHeight, baseWidth, baseHeight) {
if( imgWidth <= defaults.width && imgHeight <= defaults.height ){
return {
success: true,
width: imgWidth,
height: imgHeight
}
} else {
imgWidth -= 10;
imgHeight = imgWidth / baseWidth * baseHeight;
return getNewSise(imgWidth, imgHeight, baseWidth, baseHeight);
}
};
var resize = function(newImg) {
var imgWidth = newImg.naturalWidth;
var imgHeight = newImg.naturalHeight;
var baseWidth = imgWidth;
var baseHeight = imgHeight;
var result;
if( defaults.width < baseWidth || defaults.height < baseHeight ){
// フレームの枠より画像の方が大きい場合
while(true){
result = getNewSise(imgWidth, imgHeight, baseWidth, baseHeight);
if( result.success ){
break;
}
}
return {
width: result.width,
height: result.height,
marginTop: -(result.height / 2),
marginLeft: -(result.width / 2),
}
} else {
return {
width: imgWidth,
height: imgHeight,
marginTop: -(imgHeight / 2),
marginLeft: -(imgWidth / 2),
};
}
};
return(this);
};
})(jQuery);