【发布时间】:2021-12-18 21:54:18
【问题描述】:
我有一个图像列表,要按宽度对齐显示。
当我添加一个硬编码的图像列表时,一切看起来都很棒,并且图像覆盖了容器的整个宽度(请参阅下面的样式和代码):
<div class="flex-container">
<img src="https://picsum.photos/1800/1600" class="flex-item" [style.flex]="getFlexStyle(0)"/>
<img src="https://picsum.photos/180/180" class="flex-item" [style.flex]="getFlexStyle(1)"/>
<img src="https://picsum.photos/1202/722" class="flex-item" [style.flex]="getFlexStyle(2)"/>
<img src="https://picsum.photos/701/351" class="flex-item" [style.flex]="getFlexStyle(3)"/>
<img src="https://picsum.photos/602/822" class="flex-item" [style.flex]="getFlexStyle(4)"/>
<img src="https://picsum.photos/700/1400" class="flex-item" [style.flex]="getFlexStyle(5)"/>
</div>
但是当使用 *ngFor 添加相同的图片时,flex-grow 会被忽略:
<div class="flex-container">
<div *ngFor="let item of testFlexItems; let i = index">
<img [src]="item" class="flex-item" [style.flex]="getFlexStyle(i)"/>
</div>
</div>
testFlexItems=[
'https://picsum.photos/1800/1600',
'https://picsum.photos/180/180',
'https://picsum.photos/1202/722',
'https://picsum.photos/701/351',
'https://picsum.photos/602/822',
'https://picsum.photos/700/1400' ];
在这两种情况下,我都使用相同的样式:
.flex-container {
width:100%;
background-color: black;
display: flex;
flex-flow: row wrap;
place-content:stretch stretch;
gap: 10px;
cursor:pointer;}
.flex-item {
height:150px;
max-width: 100%;
object-fit: cover;}
还有一个辅助函数(只是为每个图像赋予不同的值 flex-grow):
flexValueArray=[4, 2, 5, 7, 3, 2, 6, 4, 3, 2];
getFlexStyle(index) {
let currentIndex = index % 10; //get the unity digit of the index e.g. index = 53 -> currentIndex = 3
let flexGrowValue = this.flexValueArray[currentIndex];
return `${flexGrowValue} 1`; }
似乎 flex 在使用 *ngFor 在每一行中添加项目时无法计算剩余宽度,但在提前给出所有图像时确实知道。 我试图寻找一种方法来告诉 flex 在所有项目加载后“重新渲染”,但没有找到任何方法。
【问题讨论】:
-
您是否尝试将
*ngFor放在img标签上,而不是放在周围的div上? -
@R.Richards 它确实是这样工作的!但是它并没有真正帮助我,因为'img'标签只是一个占位符,就示例而言。实际代码更复杂,包含一个包含“img”的“a”标签...
-
你能在图片上使用
(click)而不是锚标签吗?然后在打字稿代码中进行任何导航。