You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Div展开时ngx-masonry图片尺寸自适应且仅显示两行?

我的尝试

HTML

<div #outerDiv style="width: 500px; height: 500px; background: yellow; overflow-x: auto; white-space: nowrap;">
  <as-split direction="vertical">
    <as-split-area>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tiam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
        commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
        velit esse cillum dolore eu fugiat nulla pariatur.
      </p>
    </as-split-area>
    <as-split-area #splitArea>
      <ngx-masonry [options]="masonryOptions" class="masonry-container">
        <div ngxMasonryItem class="masonry-item" *ngFor="let item of masonryItems">
          <img masonryLazy loading="lazy" [src]="item.img" [style.height.px]="imageHeight" [style.width.px]="imageWidth" />
        </div>
      </ngx-masonry>
    </as-split-area>
  </as-split>
</div>

CSS

.masonry-container {
  overflow: hidden;
}

.masonry-item {
  margin: 5px;
}

TS

已将图片设置为数组对象,额外添加尺寸计算逻辑:

import { Component, ViewChild, ElementRef, OnInit, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  masonryItems = []; // 已初始化图片数组
  masonryOptions = {
    fitWidth: true,
    gutter: 5
  };
  imageHeight: number;
  imageWidth: number;
  @ViewChild('outerDiv') outerDiv: ElementRef;
  @ViewChild('splitArea') splitArea: ElementRef;

  ngOnInit() {
    this.calculateImageSize();
  }

  @HostListener('window:resize')
  onResize() {
    this.calculateImageSize();
  }

  calculateImageSize() {
    // 获取外层容器高度
    const outerHeight = this.outerDiv.nativeElement.offsetHeight;
    // 根据split分配比例计算masonry可用高度(此处按1:1分配,可按需调整)
    const masonryHeight = outerHeight / 2;
    // 计算单张图片高度:两行显示,减去间距
    this.imageHeight = (masonryHeight - this.masonryOptions.gutter) / 2;
    // 按图片宽高比计算宽度(示例为正方形,可替换为实际比例)
    this.imageWidth = this.imageHeight;
    // 同步设置split区域高度
    this.splitArea.nativeElement.style.height = `${masonryHeight}px`;
  }
}

需求实现方案

当前masonry区域存在垂直滚动条,要实现固定两行显示+随外层Div高度自适应调整图片尺寸,可以通过masonry配合动态计算实现,核心逻辑:

  1. 隐藏滚动并限制容器高度:给masonry容器设置overflow: hidden,通过计算将容器高度固定为两行图片的总高度(含间距),超出部分直接隐藏。
  2. 动态计算图片尺寸:监听外层Div的高度变化,结合split区域的分配比例,实时计算单张图片的高度,再按图片原生宽高比调整宽度,保证图片始终填满两行。
  3. 适配masonry配置:开启fitWidth让容器自动适配宽度,配合动态设置的图片尺寸,实现布局自适应。

调整后即可达到需求效果。

内容的提问来源于stack exchange,提问作者janaka ravindra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:45:39