我基本上有一组尺寸未知的图像。有些可能具有宽度>高度,反之亦然。
我需要按比例显示这些元素以适合 300x300 框。其中一些图像小于 300x300,需要放大,有些图像较大,需要缩小。
所以基本上,如果我有一个100x200的图像,我需要它以150x300显示,如果我有一个800x400的图像,它需要显示为<强>300x150。
ie one of the dimension need to be fit on the box and other dimension need to be resize as aspect ratio.
由于这是用户在数据库中选择的对象,因此我最初在 JavaScript 中尝试过此操作,但我很挣扎。我很好奇是否有一种纯粹的 CSS 方法可以做到这一点。
Hello You can use below code only use css and javascript
which will maintain your aspect ration also
<style type="text/css">
.image_box{
width: 300px;
height: 300px;
background: #FF0;
}
</style>
<div class="image_box">
<img src="1.jpg" id="imageid">
</div>
<script type="text/javascript">
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
//alert(width);
//alert(height);
if(width>height){
img.style.width = '300px';
}else{
img.style.height = '300px';
}
</script>
我是一名优秀的程序员,十分优秀!