简体   繁体   中英

Resizing image to fit its container

#foo {width: 300px; height: 400px; overflow: hidden;}

<div id="foo"></div>

this.someimage = randomImageUrl;
$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";

Now, the picture could be 200x200 or 1100x400 ... it's totally random. I can just stretch it (or reduce its size) by using:

.fooimage {width: 300px; height: 400px;}

$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";

Or I could test its size:

imgHeight = newImg.height; 
imgWidth = newImg.width;

... and maybe something like this:

if(imgHeight >400){
   $("foo").innerHTML = "<img src='"+this.someimage+"' height='400' />";
}

and browsers will do the rest.

But there must be something better. Any ideas? Thanks! :)

This is the idea behind the (poorly supported) max-width and max-height attributes. These are supposedly supported in IE7, and they're supported in everything else modern.

On the image, you could set max-width , max-height , giving support for IE > 7 and everything else, and then pick whichever you really need the most between width and height using an IE6 conditional to set that. It won't look quite the same on IE6, but it's a simple solution. (IE6 usage is down around 10%, so this isn't that bad anymore.)

Or you could use the "IE7" library and just set max-width and max-height, at the expense of another odd Javascript library.

You might want to try this:

$(window).load(function () {
    if ($('#my_image').width() > 300) {
        $('#my_image').css({'width':'300px'});
    }
});

I put it in $(window).load() because it simply doesn't work in document.ready() : the latter fires up before the images are loaded and so before their dimensions are known.

(To be more precise, in fact it also works, but only because the images are already in browser's cache. If you empty the cache, it would fail on next following display).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM