gpt4 book ai didi

javascript - 在 div 中调整 的大小和居中并保持纵横比

转载 作者:行者123 更新时间:2023-11-28 18:23:23 25 4
gpt4 key购买 nike

我有一个固定大小为 500x500 的 div。在这个 div 中,我有一个可以动态的图像标签。这意味着它的大小可以是正方形、矩形(宽度 > 高度)或垂直矩形(高度 > 宽度)。问题是我不希望这张图片被压扁,我想保持图片的纵横比。所以假设图像大小为 1000x250,那么我希望将其调整为 500x125,然后以这个 500x500 框为中心。如果尺寸为 500x1000,那么我们希望将其调整为 250x500,然后居中,左右两侧留有白色间距。

是否有一种简单的方法可以使用纯 css 来执行此操作,或者我是否需要 javascript 才能执行此操作?如何?

这是我现在的结构:

<div class="product-large" style="position: relative; overflow: hidden;"><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" alt=""><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" class="zoomImg" style="position: absolute; top: -236.43249427917618px; left: -188.05491990846681px; opacity: 0; width: 1024px; height: 714px; border: none; max-width: none;"></div>

最佳答案

针对垂直居中进行了更新 - 需要 jQuery。

HTML

<div class="product-large">
<img src="image1.jpg">
</div>
<div class="product-large">
<img src="image2.jpg">
</div>

CSS

.product-large {
width:500px;
height:500px;
border:1px red solid;
position:relative;
}
.product-large img {
max-width:500px;
max-height:500px;
width:auto;
height:auto;
position:absolute;
top:50%;
left:50%;
}

Javascript (jQuery)

$(".product-large img").each(function () {
//get height and width (unitless) and divide by 2
var hWide = ($(this).width()) / 2; //half the image's width
var hTall = ($(this).height()) / 2; //half the image's height, etc.

// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';

$(this).addClass("js-fix").css({
"margin-left": hWide,
"margin-top": hTall
});
});

新 fiddle :http://jsfiddle.net/Asvdk/2/

关于javascript - 在 div 中调整 <img> 的大小和居中并保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16352161/

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