我正在使用 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/