orbit-4-2/app/assets/javascripts/lib/jquery.lite.image.resize.js

125 lines
3.5 KiB
JavaScript

/* ===================================================
* jquery-lite-image-resize v.1.0.1
* https://github.com/RayChang/jquery-lite-image-resize
* ===================================================
* How to use ?
*
* HTML element closest to the image to add class "resizeimg".
*
* Example:
* <div class="resizeimg">
* <img src="images url" />
* </div>
*
* Or you can use:
* $('your class').rsImg();
*
* Note : HTML structure must be a structure like the example above.
*
*/
!function ($) {
"use strict";
var ResizeImg = function(element) {
this.element = $(element);
this.element.data('exists', true);
};
ResizeImg.prototype.resize = function() {
var $img = this.element.children('img').eq(0),
elW = this.element.innerWidth(),
elH = this.element.innerHeight(),
elScale = elW/elH,
image = document.createElement("img");
image.src = $img.attr('src');
this.element.css({
'position': 'relative',
'overflow': 'hidden',
});
function imageLoadComplete() {
var imgW = image.width,
imgH = image.height,
imgScale = imgW/imgH,
portrait = {
'position': 'absolute',
'height': '100%',
'width': 'auto',
'max-width': 'none',
'left': '50%',
'top': 0,
'margin-left': imgW*(elH/imgH)/-2
},
landscape = {
'position': 'absolute',
'height': 'auto',
'max-height': 'none',
'width': '100%',
'left': 0,
'top': '50%',
'margin-top': imgH*(elW/imgW)/-2
},
center = {
'position': 'absolute',
'height': '100%',
'width': '100%',
'top': 0,
'left': 0
};
if(imgScale < 1) {
if(elScale < 1) {
if(elScale > imgScale) {
$img.css(landscape);
} else {
$img.css(portrait);
};
} else {
$img.css(landscape);
};
};
if(imgScale > 1) {
if(elScale > 1) {
if(elScale > imgScale) {
$img.css(landscape);
} else {
$img.css(portrait);
};
} else {
$img.css(portrait);
};
};
if(imgScale == 1) {
if(elScale < 1) {
$img.css(portrait);
} else if(elScale > 1) {
$img.css(landscape);
} else {
$img.css(center);
};
};
$img.fadeTo(500, 1);
}
if(/MSIE 8.0/g.test($ua)) {
imageLoadComplete();
} else {
image.onload = imageLoadComplete;
}
};
$.fn.rsImg = function () {
this.each(function () {
if(!$(this).data('exists')) {
$(this).children("img").fadeTo(0,0);
new ResizeImg(this).resize();
};
});
};
$(function() {
$('.resizeimg').rsImg();
});
}(window.jQuery);