html - 当我不知道图像的纵横比时,如何避免 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;
}
解决方案
您可以在代码(内存)中创建一个 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
并阅读它offsetWidth
,offsetHeight
因为它存在于页面中,然后相应地更改样式并显示图像。
编辑:这是我自己以 Angular-ly 方式完成的上述堆栈闪电战。它转换onload
为Observable
,预取图像,进行一些计算,然后使用 将Renderer2
其附加到 DOM。如果您希望一个维度最大为 200 像素,我正在计算如何保持纵横比,但这只是一个示例。
推荐阅读
- c# - 抛出了 InvalidOperationException
- windows - 我应该/我需要签署外国 DLL 吗?
- neo4j - 根据条件过滤返回路径中的所有节点
- java - 快速上升到缓慢上升 整数插值
- linux - 在 LUA 中使用传递的参数执行脚本以控制 Raspberry PI 3
- spring-boot - 如何在 SpringBoot kotlin 中使用 application.yaml 中的变量
- python - 用户信息命令
- laravel - 如何使用 Laravel 和 Blade 在创建表单中仅选择属于特定课程的课程
- python - 乘法和附加python
- tooltip - 如何在 Altair 中创建显示多个字段值的工具提示?