gpt4 book ai didi

javascript - 如何调整图像大小并保持可缩放性

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:10 24 4
gpt4 key购买 nike

当我将所有 jpg 调整为相同大小时,布局工作正常。但是当它们的尺寸不同时,它们就不能很好地适合我的 div。我添加了一个显示问题的代码片段。最后两张图竖的有点大

这是我的 HTML 和 CSS

#firstSection {
width: 50%;
float: left;
}
.otherSections {
width: 25%;
float: left;
overflow: hidden;
}
img {
display: block;
width: 100%;
}
@media only screen and (max-width: 479px) {
#firstSection,
.otherSections {
clear: both;
width: 100%;
}
}
<main>
<section id='firstSection' >
<img alt="DSC_001.jpg" src="http://www.sailwbob.com/skipper/public/img/DSC_001.JPG"/>
</section>
<section class='otherSections'>
<img alt="DSC_002.jpg" src="http://www.sailwbob.com/skipper/public/img/DSC_004.jpg"/>
<img alt="DSC_003.jpg" src="http://www.sailwbob.com/skipper/public/img/DSC_005.jpg"/>
</section>
<section class='otherSections'>
<img alt="DSC_002.jpg" src="http://www.sailwbob.com/skipper/public/img/DSC_004a.JPG"/>
<img alt="DSC_003.jpg" src="http://www.sailwbob.com/skipper/public/img/DSC_005b.jpg"/>
</section>
</main>

最佳答案

如果您所有的图像都具有相同的宽度/高度比(或者至少大致相同,例如所有示例图像中的 3:2),您可以使用背景图像和一些 javascript 来实现:

1.) 创建空 DIV,将它们的宽度设置为 50% 或 25%

2.) 使用 background-size: coverbackground-repeat: no-repeat

将背景图像应用于所有这些图像

3.) 由于 DIV 没有高度(背景图像不算作内容),您必须定义它们的高度:使用 javascript 获取父元素(窗口?)的宽度

4.) 根据宽度百分比和图像比例计算高度并通过javascript设置为高度。对于 25% 宽的 DIV,高度为 parentwidth * 0.25 * 2/3,对于 50% 宽的 DIV parentwidth * 0.5 * 2/3

补充:

这是我完成所有这些工作的代码笔:http://codepen.io/anon/pen/Bpmxxd

下面是一个片段:

parentwidth = $('main').innerWidth();

height1 = parentwidth * 0.5 * 2/3;
$('#firstSection').height(height1);

height2 = parentwidth * 0.25 * 2/3;
$('.otherSections').height(height2);
main {
border: 1px solid red;
overflow: hidden;
}
#firstSection {
background: url(http://www.sailwbob.com/skipper/public/img/DSC_001.JPG) no-repeat center;
width: 50%;
float: left;
}
.x1 {
background: url(http://www.sailwbob.com/skipper/public/img/DSC_002.JPG) no-repeat center;
}
.x2 {
background: url(http://www.sailwbob.com/skipper/public/img/DSC_003.JPG) no-repeat center;
}
.x3 {
background: url(http://www.sailwbob.com/skipper/public/img/DSC_004a.JPG) no-repeat center;
}
.x4 {
background: url(http://www.sailwbob.com/skipper/public/img/DSC_001.JPG) no-repeat center;
}
.x1, .x2, .x3, .x4 {
width: 25%;
float: left;
}

#firstSection, .otherSections {
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<main>
<section id='firstSection'>
</section>
<section class='otherSections x1'>
</section>
<section class='otherSections x2'>
</section>
<section class='otherSections x3'>
</section>
<section class='otherSections x4'>
</section>

</main>

关于javascript - 如何调整图像大小并保持可缩放性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41903936/

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