首页 > 解决方案 > 当我不知道图像的纵横比时,如何避免 Angular 中的图像重排?

问题描述

我正在尝试使用padding bottom hack(如下图所示)在 Angular 网站的图像加载时停止重排。问题是我不知道图像的纵横比,因为它是用户指定的。当图像尺寸未知时,是否可以停止图像重排?我找到了使用 javascript 获取图像尺寸的示例,但这似乎是在页面加载后发生的。我可以在加载之前获取组件中图像的高度和宽度吗?我可以访问组件中的图像源。

index.html
----------
<div class="img-wrapper" style="padding-bottom: calc((400/600)*100%);">
  <img src="example.jpg" />
</div>

styles.css
----------
.img-wrapper {
  position: relative;
  display: block;
  height: 0;
  overflow: hidden;
}

.img-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  max-width: inherit;
}

标签: htmlcssangular

解决方案


您可以在代码(内存)中创建一个 JavascriptImage对象并以这种方式读取纵横比。

let image = new Image();
let width: number;
let height: number;

image.onload = () => {
  { height, width } = image;
  const ratio = width / height;
}

newImg.src = 'Your source here'; // this must be done AFTER setting onload and will load the image.

请记住,设置src图像的 将加载它,这是异步的。onload是加载图像时的回调。

您也可以通过img标签将其加载到页面中,最初对其进行样式设置,使其不可见并且不会弄乱页面布局(position: absolute; opacity: 0或类似的东西),然后使用 抓取元素Renderer2并阅读它offsetWidthoffsetHeight因为它存在于页面中,然后相应地更改样式并显示图像。

编辑:这是我自己以 Angular-ly 方式完成的上述堆栈闪电战。它转换onloadObservable,预取图像,进行一些计算,然后使用 将Renderer2其附加到 DOM。如果您希望一个维度最大为 200 像素,我正在计算如何保持纵横比,但这只是一个示例。


推荐阅读