html - 在圖像畫廊中使用虛擬滾動
我正在嘗試在我的圖片畫廊中實現虛擬滾動。我的問題是實現效果不正確。首先,元素是以垂直排列顯示的,實際上它們應該遵循水平斷點,然後再遵循垂直滾動。其次,滾動時元素之間出現了很大的間距。
有人知道我該如何解決這個問題嗎?謝謝
示範
HTML
<div [ngSwitch]="viewMode" style="height:100%; width:100%">
<div id="tab2" *ngSwitchCase="'tab2'" style="height:100%; width:100%">
<div
style="margin-left: 16px; margin-right: 16px;height:100%; width:100%"
class="first"
>
<ng-container
*ngIf="
arrayDeNomesCategorias.length == 0 ||
arrayDeNomesCategorias == undefined
"
>
<ul
class="mdc-image-list my-image-list"
style="height:100%; width:100%"
>
<cdk-virtual-scroll-viewport
itemSize="50"
style="height:100%; width:100%"
>
<ng-container *cdkVirtualFor="let i of images; let j = index">
<li class="mdc-image-list__item">
<div class="mdc-image-list__image-aspect-container">
<img
src="https://material-components-web.appspot.com/images/photos/3x2/{{
i + 1
}}.jpg"
class="mdc-image-list__image"
/>
</div>
</li>
</ng-container>
</cdk-virtual-scroll-viewport>
</ul>
</ng-container>
</div>
</div>
</div>
問題
正確,但沒有實現捲動功能 :(
答案#1
我在這裡更新了你的範例。
你的問題主要出在 CSS,而且似乎至少有兩個問題:
你正在給
.mdc-image-list__item類別設置min-height: 400px和max-height: 400px。這基本上意味著你所有的.mdc-image-list__item容器高度都將是 400px(所以 height: auto 就變得沒有用)。刪除這個將會移除你圖片之間的空白。如果你想在同一頁面上同時擁有滾動效果和元素,你應該使用帶有
flex-wrap: wrap的彈性容器。
為了做到這一點,我使用了以下程式碼片段(針對你的情況):
:host ::ng-deep .cdk-virtual-scroll-content-wrapper {
display: flex;
flex-wrap: wrap;
}
你可以在這裡閱讀更多關於 host 和 ng-deep 的資訊。但請注意,根據這篇文章(不僅僅是這篇)建議在最新版本的 Angular 中避免使用它。為了簡單起見,我在你的範例中使用了它,但你可能想在正式環境中避免使用它。
- (額外) :作為一個小的改進,我還移除了
.mdc-image-list__item媒體查詢中重複的margin: 10px; height: auto; max-height: 400px;屬性(只保留了沒有媒體查詢的初始那一個)。無論如何,它都會被應用,因為沒有其他東西覆蓋它,而只在媒體查詢中更改寬度應該就足夠了。

