我想创建一个组件,在左侧或右侧有一个文本,旁边有一个图像。
目前我只使用一个 bool 参数来检查哪个元素先出现。在较大的屏幕尺寸上一切都很好,但当涉及到较小的屏幕尺寸时,每个图像都应位于文本上方。
如果文本在左侧,这将不起作用,因为它会将自己置于图像上方。
我创建了一个显示问题的工作示例
https://codesandbox.io/s/3qpj23y3o1
我该如何解决这个问题?也许也有办法摆脱这个 if 语句?因为唯一不同的是图像和文本容器的顺序。
最佳答案
由于您使用的是 CSS 网格,因此您可以简单地通过使用 grid-template-areas
并创建您的区域 img
和 txt
:
.textImageSectionContainer {
...
grid-template-areas:'img' 'txt';
}
.imgContainer {
....
grid-area:img;
}
.txtContainer {
padding: 50px;
grid-area:txt;
}
在这个 codesandbox 中,您只能对小尺寸应用上述规则。例如,我将上述屏幕尺寸规则设置为 700 像素以下
更新:
您可以使用类绑定(bind)来避免 if
语句和冗余代码:
<template>
<div
:class="{ imgleft: imageLeft, imgright: !imageLeft }"
class="textImageSectionContainer"
>
<div class="imgContainer"><img :src="imgUrl" class="img" /></div>
<div class="txtContainer">
<div class="headerText">{{ headerText }}</div>
<div class="mainText">{{ mainText }}</div>
</div>
</div>
</template>
CSS 规则应该是这样的:
.imgleft {
display: flex;
}
.imgright {
display: flex;
flex-direction: row-reverse;
}
关于javascript - 在不同的屏幕尺寸上重新排序 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791139/