2011-05-14 40 views
1

网页需要显示一些图像。而且,图像应该显示为适合正方形(90 * 90像素)。不幸的是,图像的大小是不可预知的。它们可能是80 * 100或100 * 80或90 * 110.如何拉伸图像以适合网页中的正方形?

要求将图像拉伸为:
1)如果图像的宽度为45,高度为100,则将其宽度拉伸至90,将高度拉伸至200。显示其前90个像素。
2)如果图像的宽度为100,高度为45,则将其宽度扩展到200,将高度扩展到90.显示其左侧90像素。

总之,图像的左上部分总是90 * 90的大小。

它在JavaScript和CSS中的解决方案是什么? 感谢

回答

2

这会做到这一点?

<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;background-image:url('myImage.jpg');background-size:100%;"></div> 

例如在http://snuzzer.dk/pub/fit_image_to_div.html

UPDATE:

我已经改变了它使用JavaScript来代替。这应该解决宽度/高度的问题,没有显示正确使用纯CSS方法。以http://snuzzer.dk/pub/fit_image_to_div.html为例。

<script type="text/javascript"> 
function fitImage(src) { 
    var image = new Image(); 
    image.src = src; 
    var height = image.height; 
    var width = image.width; 

    if(width > height) { // Image is wider than it's high 
     scale = 90/height; 
    } 
    else { // Image is higher than it's wide 
     scale = 90/width; 
    } 

    image.width = width * scale; 
    image.height = height * scale; 

    document.getElementById('info').innerHTML = width + 'x' + height + ' => ' + image.width + 'x' + image.height; 

    document.getElementById('container').style.backgroundImage = 'url(' + image.src + ')'; 
    document.getElementById('container').style.backgroundSize = image.width + 'px ' + image.height + 'px'; 
} 
</script> 
<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;" id="container"></div> 
<div id="info"></div> 
URL to an image: <input type="text" id="url" style="width:400px;" /> 
<br /> 
<input type="button" value="Fit images" onClick="fitImage(document.getElementById('url').value)" /> 
+0

这工作。谢谢 – 2011-05-14 09:03:23

+0

2011-05-14 09:09:56

+0

但是,如果原始图像的宽度大于高度,此技巧无法正常工作。 – 2011-05-14 09:10:27

0

你只需把所需的宽度和高度的图像html标记这样

<img src="myimgae.jpg" width="90" height="90"/> 
+0

这会影响高度/宽度的比例。 – 2011-05-14 09:01:53

+0

如果你想保持口粮只是把宽度或高度,其他值将动态获得。 – 2011-05-14 10:51:06