我想将图像放入 div 中。但是,当 div 更改大小时,div 中包含的图像不会保留在 div 内。以下是 div 具有“正常”大小时的图像:
以下是改变 div 大小时的图像:
当图像不适合 div 时,我希望 div 添加滚动条。 这是一些代码:
// Here is where the tag <img /> is created:
function getData(id) {
$.get(`/api/IgnicoesAPI/${id}`, function(data) {
$('#header').append('<h3 style="text-align:center;"><b>Avaliação da Ignição</b></h3>');
$('#myDiv').append('<p>Estado:' + data.estado + '</p>')
$('#myDiv').append('<p>ID: ' + id + '</p>');
$.each(data.listaOcorrencias, function(o, ocorrencia) {
//Adding images
$('#myDiv').append('<img src="imagensFogos/' + ocorrencia.fotografia + '" onclick="openModal();" class="hover-shadow" style="width:200px; height:190px;" hspace="4"/>');
});
//MORE CODE
});
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.buttonsClass {
position: absolute;
bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div id="header" class="headerClass"></div>
//Here is where the images are stored
<div id="myDiv" class="added">
</div>
<div id="buttons" class="buttonsClass"></div>
</div>
</div>
最佳答案
使用 display: flex
强制所有图像排成一行,然后添加 overflow-x: auto
在需要时添加水平滚动条。
.modal-content {
width: 400px;
padding: 20px;
border: darkgrey solid 2px;
}
#myDiv {
max-width : 100%;
overflow-x : auto;
border : blue dashed 1px;
display : flex;
}
img{
margin-right : 10px;
}
<div class="modal-content">
<div id="myDiv" class="added">
<img src="https://picsum.photos/200/150" />
<img src="https://picsum.photos/190/150" />
<img src="https://picsum.photos/195/150" />
<img src="https://picsum.photos/150/150" />
</div>
</div>
关于javascript - 当 div 改变大小时,如何修复 div 内图像的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60394039/