不间断水平滚动的纯CSS文本滚动效果

37

我正在尝试创建一个新闻滚动条,水平文字可以连续滚动而不会在循环之间产生中断。理想情况下,解决方案将是纯CSS/HTML,但我不知道是否可能。这是到目前为止我粗略的尝试:http://jsfiddle.net/lgants/ncgsrnza/。请注意,代码包含每个循环之间的不必要的中断。

<p class="marquee"><span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text</span></p>


    .marquee {
        margin: 0 auto;
        white-space: nowrap;
        overflow: hidden;
    }
    
    .marquee span {
        display: inline-block;
        padding-left: 100%;
        animation: marquee 5s linear infinite;
    }
2个回答

74

您可以尝试使用两个跑马灯,将其中一个设置为延迟2.5秒的动画,这是完整动画时间(5秒)的一半。

.marquee {
  margin: 0 auto;
  white-space: nowrap;
  overflow: hidden;
  position: absolute;
}

.marquee span {
  display: inline-block;
  padding-left: 100%;
  animation: marquee 5s linear infinite;
}

.marquee2 span {
  animation-delay: 2.5s;
}

@keyframes marquee {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-100%, 0);
  }
}
<p class="marquee">
  <span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text -&nbsp;</span>
</p>
<p class="marquee marquee2">
  <span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text -&nbsp;</span>
</p>


2
只是一条注释:为了使这个概念起作用,没有必要复制关键帧(marquee2)。 - Jonathan
1
如果文本太短,您可以继续复制跑马灯并调整动画延迟。或者,您可以使用JS在特定时间间隔内删除/添加带有动画的类,但@lgants想要纯CSS / HTML。 - rmurph46
10
通过为第一个span添加负的动画延迟,并将第二个span的延迟设置为0,我成功地使文本从左侧开始滚动。.marquee1 span { animation-delay: -2.5s; } .marquee2 span { animation-delay: 0s; } - Andrew Hawes

22

这与上面的答案类似。我从Next.js的官方网站上获取了这个示例。他们将其与SVG一起使用,制作了一个滑块来显示哪些知名公司正在使用他们的框架。

.wrapper {
  max-width: 100%;
  overflow: hidden;
}

.marquee {
  white-space: nowrap;
  overflow: hidden;
  display: inline-block;
  animation: marquee 10s linear infinite;
}

.marquee p {
  display: inline-block;
}

@keyframes marquee {
  0% {
    transform: translate3d(0, 0, 0);
  }
  100% {
    transform: translate3d(-50%, 0, 0);
  }
}
<div class="wrapper">
  <div class="marquee">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce volutpat, ante eu bibendum tincidunt, sem lacus vehicula augue, ut suscipit.
    </p>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce volutpat, ante eu bibendum tincidunt, sem lacus vehicula augue, ut suscipit.
    </p>
  </div>
</div>


这取决于容器的宽度。如果宽度很高,当在页面中间时,文本会突然显示出来。 - Martin Meeser
@MartinMeeser 你说得没错。但这取决于特定的(用户)浏览器能够多快地呈现移动段落(尤其是在X轴平移之前)。通过减缓动画可以在一定程度上避免这种情况的发生。 - brc-dd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接