I need to fit images to the viewport/window size.
I use this code for doing it:
$(".fittedImg").each(function () {
// I want to limit the size, and show a scrollbar on very small viewport
height = ($(window).height() < 725) ? 725 : $(window).height();
width = ($(window).width() < 1150) ? 1150 : $(window).width();
var newWidth, newHeight;
$(this)
.removeAttr("height")
.removeAttr("width"); // reset img size
// calculate dimension and keep it
if (($(this).width() / width) > ($(this).height() / height)) {
newHeight = height;
newWidth = height / ($(this).height() / $(this).width());
} else {
newHeight = width / ($(this).width() / $(this).height());
newWidth = width;
};
$(this).stop(true, false).animate({
"height": newHeight + "px",
"width": newWidth + "px"
});
});
I wrapped that code in a function which I call on resize, and on events such as $('.fittedImg').load() and $('.fittedImg').ready().
The result's very weird: In Chrome it normally works, but somtimes the images stretch on repeated refreshes. On IE there's quite the same problem. Opera does not fail never and safari ignore the calculation at all (ever stretching).
What's wrong with my calculation and/or events calling?
Thank you.
Assuming you want to fit the image inside a containing element (in this case the window
), here are some simpler calculations you might find useful. The concept is quite simple, based on the containing measures and the image measures, calculate a ratio. Then multiply it with the original measures:
$(".fittedImg").load(function(){
var imgWidth = this.width,
imgHeight = this.height,
winWidth = $(window).height(),
winHeight = $(window).width(),
ratio = Math.min(winWidth/imgWidth, winHeight/imgHeight);
// if you don’t want it to upscale, use Math.min or Math.max on the ratio
$(this).stop(true, false).animate({
height: imgHeight*ratio,
width: imgWidth*ratio
});
});
Please note that some extensions such as AdBlock can mess up the extracted width/height from the image. You can console and text the imgWidth
/ imgHeight
just to make sure that it is available.
Also please note that chances are that your image is already loaded when this event is added, depending on how you place your code. In that case, you should check for the complete
property on the IMG element:
$('fittedImg').each(function() {
$(this).load(function() {
// the calculations goes here
});
if (this.complete) { // check if image is already loaded
$(this).trigger('load');
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.