如何防止动画滚动文本在 HTML/CSS 中突然重新启动?



我制作了这个代码笔来演示我在说什么:https://codepen.io/sakana-boy/pen/wvBedWo

.scroll-text {
overflow: hidden;
position: relative;
}
.scroll-text * {
white-space: pre;
transform: translateX(100%);
animation: scroll 5s steps(70, end) infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
<div class="scroll-text" style="width: 355px;">
<div>hi i am very long text lolololololoololo this is very long sdafkalshgjalwke more text wow ok TOO LONG!!! you Will not See THIS text because it gets cut off : ( very sad </div>
</div>
<div class="scroll-text" style="width: 355px;">
<div>this text is shorter so all the text properly is shown</div>
</div>

基本上,我有计划动态填充的文本,我想在狭窄的父div(而不是文本(中滚动文本。正如您在上面的代码笔中看到的,滚动在动画中间突然重新启动。我可以将 translateX 的 100% 关键帧设置为具有更高(更低?(的值,但是由于文本是动态的,因此我无法提前知道该值。此外,如果该值太高,则较短的文本在文本框中具有较长的空白期。

有没有办法动态分配关键帧 0% 和 100% 值,以便我让整个文本显示在动画中?第二行是所有文本应如何滚动(即,在重新启动之前显示所有内容(。另外,我不想增加父div的宽度,因为这会导致文本溢出到其他元素中(在我的真实网页中(。

如果单独使用 HTML 和 CSS 无法做到这一点,我愿意使用 Javascript(最好是原版 JS,所以我不需要包含 jQuery(。

使用position: relativetransform

  • transform: translateX(100%)使用 100% 大小的内容(文本(;
  • position: relative; left: 100%. 使用100%尺寸的容器;

使用display: table,使内div的宽度适合其内容。

.scroll-text {
overflow: hidden;
position: relative;
}
.scroll-text * {
display: table;
white-space: pre;
position: relative;
animation: scroll 5s linear infinite;
}
@keyframes scroll {
0% { left: 100%; transform: translateX(0); }
100% { left: 0; transform: translateX(-100%); }
}
<div class="scroll-text" style="width: 355px;">
<div>hi i am very long text lolololololoololo this is very long sdafkalshgjalwke more text wow ok TOO LONG!!! you Will not See THIS text because it gets cut off : ( very sad </div>
</div>
<div class="scroll-text" style="width: 355px;">
<div>this text is shorter so all the text properly is shown</div>
</div>

最新更新