网页需要显示一些图片。并且,应该显示图像以适合方形(90 * 90像素)。不幸的是,图像的大小是不可预测的。它们可能是80 * 100或100 * 80或90 * 110。
要求是将图像拉伸为:
1)如果图像的宽度为45,高度为100,则将其宽度拉伸至90,将高度拉伸至200.显示其前90个像素
2)如果图像宽度为100且高度为45,则将其宽度拉伸至200,将高度拉伸至90.显示其左侧90像素。
总之,图像的左上角始终为90 * 90。
JavaScript和CSS的解决方案是什么? 感谢
答案 0 :(得分: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
上的示例<强>更新强>
我已将其更改为使用JavaScript。这应该解决宽度/高度没有显示正确使用CSS-only方法的问题。请查看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)" />
答案 1 :(得分:0)
您只需将所需的宽度和高度放在图像html标签中,就像这样
<img src="myimgae.jpg" width="90" height="90"/>