javascript - 调整未知尺寸和纵横比的图像大小

标签 javascript css image

我基本上有一组尺寸未知的图像。有些可能具有宽度>高度,反之亦然。

我需要按比例显示这些元素以适合 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>

关于javascript - 调整未知尺寸和纵横比的图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602345/

相关文章:

html - "Crop"使用 CSS 的照片

javascript - 如何使 Html 表格列可编辑?

javascript - 顺序函数javascript

css - 平滑 CSS3 动画

angular - 在使用 Angular 在 Firebase 中上传之前调整大小和压缩图像质量

HTML5 源代码集 : Mixing x and w syntax

javascript - 还是不明白 RXJS operator combineLatestAll 是如何工作的?

javascript - 避免在javascript中转义特殊字符

html - bootstrap div 100% 高度

Javascript 在滚动时显示/隐藏菜单