javascript - 在不同的屏幕尺寸上重新排序 DOM 元素

标签 javascript css vue.js vuejs2 vue-component

我想创建一个组件,在左侧或右侧有一个文本,旁边有一个图像。

enter image description here

目前我只使用一个 bool 参数来检查哪个元素先出现。在较大的屏幕尺寸上一切都很好,但当涉及到较小的屏幕尺寸时,每个图像都应位于文本上方。

如果文本在左侧,这将不起作用,因为它会将自己置于图像上方。

我创建了一个显示问题的工作示例

https://codesandbox.io/s/3qpj23y3o1

我该如何解决这个问题?也许也有办法摆脱这个 if 语句?因为唯一不同的是图像和文本容器的顺序。

最佳答案

由于您使用的是 CSS 网格,因此您可以简单地通过使用 grid-template-areas 并创建您的区域 imgtxt :

   .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/

相关文章:

html - CSS:在页面上扩展一行宽度

css - Topmargin 0 不起作用?缓存问题?

vue.js - 定义 Vuetify 3 配置默认值的问题

javascript - 视觉 : Getting the router instance in children components

javascript - VideoJS - 无法销毁和初始化

javascript从字符串数组构造一个对象

javascript - 如何修复 React Context 的对象不是函数 - TypeError

javascript - 如何在 Visual Studio Code 中执行 AngularJS

html - 图片背后的文字

javascript - 带数组的 vue.js v 模型