gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:21:29 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com