angular:简单实现图片如果超过屏幕高度则滚动置顶;没超过则水平垂直居中

发布于:2023-09-15 ⋅ 阅读:(76) ⋅ 点赞:(0)

问题:

        如题

解决办法:

        

  <div #imgRoot style="position: absolute; background-color: slategray; width: 100%; height: 100%;">
    <div #imgContainer style="background-color: slategray; padding: 3px 0; display: flex; flex-direction: row; justify-content: center; align-items: center; width: 100%;">
      <img #img [src]="imgSrc" width="90%" alt=""/>
      <ng-container
        *ngIf="(img.height < imgRoot.offsetHeight)?
          imgContainer.setAttribute('style', imgContainer.getAttribute('style')+';height: 100%')
          : imgContainer.setAttribute('style', imgContainer.getAttribute('style')+';height: auto')">
      </ng-container>
    </div>
  </div>

额外说明:

        此写法针对简单界面有效,因为ngif中有函数,会触发多次调用,如果含复杂界面可能会有性能问题。

        求轻快实现可以一步在html模板里完成,而不用去ts中搞一堆代码

        如果有其他简单实现也可以在评论区告诉我,谢谢了


网站公告

今日签到

点亮在社区的每一天
去签到