在绝对 Div 中以固定高度交叉淡入淡出文本的最佳方法?

问题描述 投票:0回答:1

我想在特定宽度的容器 div 中淡入淡出多个具有不同长度的文本引用(来自 CMS)。 这是我想出的,但现在是 2024 年了,我觉得 has 是一种更简单的方法来做到这一点,要么只使用 CSS,要么不必使用

onResize
。我正在做的是将所有引号循环两次:一次用于显示,另一次用于大小计算 - 确定最高的引号并将父 div 设置为该高度。

我不想导入画廊/轮播库或 js 框架作为看似简单的东西的依赖项。只是想知道是否有人有任何简化这个的想法。谢谢!


screenshot of codepen

javascript html css-animations absolute
1个回答
0
投票

您可以考虑使用 CSS 网格系统。使

.wrapper
成为由一个网格区域组成的网格布局。让引号全部占据同一网格区域。这允许它们重叠,同时最高的一个决定网格元素的大小。

const wrapperEl = document.getElementById('wrapper')

const animTimer = setInterval(() => {
  if (!wrapperEl) {
    return
  }

  const active = wrapperEl.querySelector('.active')
  let next = active ? .nextElementSibling
  if (!next) {
    next = active ? .parentElement ? .firstElementChild
  }

  active ? .classList.remove('active')
  next ? .classList.add('active')
}, 4500)
:root {
  --width: 70%;
}

.wrapper {
  display: grid;
  grid-template: 1fr / 1fr;
  align-items: center;
  width: var(--width);
  /* or any specific width */
  min-height: 200px;
  background-color: #efefef;
  overflow: hidden;
}

.wrapper>div {
  opacity: 0;
  grid-area: 1 / 1 / -1 / -1;
  /* padding: 20px; */
  font-size: 40px;
  font-weight: bold;
  background-color: #ccf;
  transition: opacity 0.5s;
}

.wrapper .active {
  opacity: 1;
}

blockquote {
  margin: 0;
  padding: 0;
}

cite {
  display: inline-block;
  font-size: 1.5rem;
  padding-block-start: 20px;
}

p {
  width: var(--width);
}
<p>
  Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site.
</p>
<div id="wrapper" class="wrapper">
  <div class="active">
    <blockquote>"This is a medium quote or possibly just a regular one."</blockquote>
    <cite>-Mark Twain</cite>
  </div>
  <div>
    <blockquote>"This is a short quote."</blockquote>
    <cite>-Jeb Lawrence</cite>
  </div>
  <div>
    <blockquote>"This is quite possibly the longest quote known to anyone who has lived on earth and ever knew anything about what it takes to make a good quote."</blockquote>
    <cite>-Morgan Freeman</cite>
  </div>
  <div>
    <blockquote>"This is another somewhat long quote, or depending on your point of view, a short one."</blockquote>
    <cite>-Chris Smith</cite>
  </div>
</div>

<p>
  Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site. Welcome to this web site.
</p>

© www.soinside.com 2019 - 2024. All rights reserved.