开发者

Proportional image scaling

开发者 https://www.devze.com 2023-03-30 21:08 出处:网络
I have a div of known size and a link to some image with random size, which i want to show inside this div. I would like an image to have proportional scaling, to be as big as posible, but no bigger t

I have a div of known size and a link to some image with random size, which i want to show inside this div. I would like an image to have proportional scaling, to be as big as posible, but no bigger than div (either the image width should equal the div's width or the image height should equal the div's height, but i dont ex开发者_运维问答actly know which case).

How could i do it using only html, css, javascript and jquery? And it would be great not to read the image size.


You can do this with pure CSS by setting max-width and max-height to 100%. This is a great article to read on the subject: http://unstoppablerobotninja.com/entry/fluid-images. The article also discusses how to deal with older versions of IE.

Here's an example of the CSS in action - http://jsfiddle.net/JamesHill/R7bAA/

HTML

<div id='div1'>
    <img class='myImageClass' src='http://www.google.com/intl/en_com/images/srpr/logo3w.png' />
</div>
<br />
<div id='div2'>
    <img class='myImageClass' src='http://www.google.com/intl/en_com/images/srpr/logo3w.png' />
</div>

CSS

#div1
{
    height:100px;
    width:200px;
    background-color:Gray;
    border: 1px solid Black;
}
    #div2
{
    height:500px;
    width:100px;
    background-color:Gray;
    border: 1px solid Black;
}
.myImageClass
{
    max-height:100%;
    max-width:100%;
}


Here's a javascript method that computes the aspect ratio of image and container and sets the corresponding height or width value that will first hit the edge and the image then scales the other dimension proportionally:

// pre-cache image
var img1 = new Image();
img1.src = "http://photos.smugmug.com/photos/344291068_HdnTo-L.jpg";
var img2 = new Image();
img2.src = "http://photos.smugmug.com/photos/344291068_HdnTo-L.jpg";

function placeImage(imgObj, containerID) {
    var container = $(containerID);
    var imageAspectRatio = imgObj.height / imgObj.width;
    var containerAspectRatio = container.height() / container.width();
    // figure out which dimension hits first and set that to match
    if (imageAspectRatio > containerAspectRatio) {
        imgObj.style.height = container.height() + "px";
    } else {
        imgObj.style.width = container.width() + "px";
    }
    container.append(imgObj);

}

$("#go").click(function() {
    placeImage(img1, "#container1");
    placeImage(img2, "#container2");
});

You can see it here in this jsFiddle: http://jsfiddle.net/jfriend00/5K3Zf/

0

精彩评论

暂无评论...
验证码 换一张
取 消