html - 如何创建字幕效果?

标签 html css css-animations

我正在使用 CSS3 动画创建选取框效果。

#caption {
    position: fixed;
    bottom: 0;
    left: 0;
    font-size: 20px;
    line-height: 30px;
    height:30px;
    width: 100%;
    white-space: nowrap;
    -moz-animation:  caption 50s linear 0s infinite;
    -webkit-animation:  caption 50s linear 0s infinite;
}
@-moz-keyframes caption { 
    0% { margin-left:120%; } 100% { margin-left:-4200px; }  
}
@-webkit-keyframes caption { 
    0% { margin-left:120%; } 100% { margin-left:-4200px; }  
}
<div id="caption">
    The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog.
</div>

现在我可以得到基本的跑马灯效果了,但是代码对于这个演示来说太具体了。

有没有办法避免使用像margin-left:-4200px;这样的特定值,从而适应任意长度的文本?

这是一个类似的演示:http://jsfiddle.net/jonathansampson/XxUXD/使用 text-indent 但仍具有特定值。

最佳答案

通过对标记进行少量更改,这是我的方法(我刚刚在段落中插入了一个 span):

.marquee {
  width: 450px;
  margin: 0 auto;
  overflow: hidden;
  box-sizing: border-box;
}

.marquee span {
  display: inline-block;
  width: max-content;

  padding-left: 100%;
  /* show the marquee just outside the paragraph */
  will-change: transform;
  animation: marquee 15s linear infinite;
}

.marquee span:hover {
  animation-play-state: paused
}


@keyframes marquee {
  0% { transform: translate(0, 0); }
  100% { transform: translate(-100%, 0); }
}


/* Respect user preferences about animations */

@media (prefers-reduced-motion: reduce) {
  .marquee span {
    animation-iteration-count: 1;
    animation-duration: 0.01; 
    /* instead of animation: none, so an animationend event is 
     * still available, if previously attached.
     */
    width: auto;
    padding-left: 0;
  }
}
<p class="marquee">
   <span>
       When I had journeyed half of our life's way, I found myself
       within a shadowed forest, for I had lost the path that 
       does not stray. – (Dante Alighieri, <i>Divine Comedy</i>. 
       1265-1321)
   </span>
   </p>


未插入硬编码值(取决于段落宽度)。

动画应用了 CSS3 transform 属性(在需要的地方使用前缀),因此效果很好。

如果您只需要在开始时插入一次延迟,那么还要设置一个animation-delay。如果您需要在每个 循环中插入一个小的延迟,则尝试使用更高的padding-left(例如150%)

关于html - 如何创建字幕效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40522738/

相关文章:

css - 如何在 CSS 中添加一个类以使其在页面上具有动画效果?

jquery - 无法更改 Bootstrap 的 css

Javascript rowIndex 方法不起作用

javascript - jQuery 菜单不会在 Safari 中折叠

css - 在子菜单中保持按钮事件状态

javascript - 我如何制作具有 3 种颜色和很多曲线的多渐变背景?

jquery - 多个关键帧动画破坏了 Internet Explorer 11 中的自定义 slider

html - 有什么方法可以在 iPad 上使用 CSS 来设置 optgroup 的样式吗?

html - 需要更改列表项以便它们不会直接进入页面下方?

css - 重复多个 css 动画