使用css动画来实现文字滚动
<style>
.scroll{
width: 500px;
height: 50px;
line-height: 50px;
white-space: nowrap;
overflow: hidden;
font-size: 30px;
margin: 0 auto;
}
.scroll span{
display: inline-block;/*inline样式不能使用动画*/
animation: scroll 10s linear infinite;
}
@keyframes scroll {
from {
transform: translateX(500px)
}
to {
transform: translateX(-100%)
}
}
</style>
<div class="scroll">
<span> 断章(卞之琳创作现代诗歌) 你站在桥上看风景, 看风景人在楼上看你。 明月装饰了你的窗子,
你装饰了别人的梦。</span>
</div>
这种滚动方式体验很不好,中间有过多空白,接下来我们要实现一个首尾相连的文字滚动。
在不使用js改变DOM结构的前提下,要为span里添加重复内容我们可以使用after伪元素,它有个attr函数可以获取所在父元素的属性内容,前提只要我们提前将span里的内容同时设置到属性里比如data-text,我们就可以只使用CSS为span添加尾部内容,这对使用VUE等框架是很方便的。
<style>
/*字数滚动*/
.scroll {
width: 500px;
height: 50px;
line-height: 50px;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
margin-left: 24%;
}
.scroll span {
display: inline-block; /*inline样式不能使用动画*/
animation: scroll 20s linear infinite;
}
.scroll span:after {
content: attr(data-text);
margin-left: 4em;
}
@keyframes scroll {
from {
transform: translateX(100px);
}
to {
transform: translateX(calc(-50% - 2em)); /*总长的一半再加上margin-left的一半*/
}
}
</style>
<div class="scroll">
<span
data-text=" 断章(卞之琳创作现代诗歌) 你站在桥上看风景, 看风景人在楼上看你。 明月装饰了你的窗子,
你装饰了别人的梦。"
>
断章(卞之琳创作现代诗歌) 你站在桥上看风景, 看风景人在楼上看你。 明月装饰了你的窗子,
你装饰了别人的梦。
</span>
</div>
上面已经基本上实现了首尾相连的文字滚动了,但是带有inline性质的元素会继承上层的很多样式影响布局,同时不同浏览器对div.scroll的最终宽度计算会有偏差,导致文字滚动出现错位。为了抹平差异,我们要对after元素使用绝对定位。
<style>
.scroll{
position: relative;
width: 500px;
height: 50px;
line-height: 50px;
font-size: 30px;
white-space: nowrap;
overflow: hidden;
}
.scroll span{
display: inline-block;/*inline样式不能使用动画*/
animation: scroll 12s linear infinite;
}
.scroll span:after{
position: absolute;
left: 100%;
content: attr(data-text);
margin-left: 4em;
}
@keyframes scroll {
from {
transform: translateX(0);
}
to {
transform: translateX(calc(-100% - 4em)); /*总长再加上margin-left*/
}
}
</style>
<div class="scroll">
<span
data-text=" 断章(卞之琳创作现代诗歌) 你站在桥上看风景, 看风景人在楼上看你。 明月装饰了你的窗子,
你装饰了别人的梦。"
>
断章(卞之琳创作现代诗歌) 你站在桥上看风景, 看风景人在楼上看你。 明月装饰了你的窗子,
你装饰了别人的梦。
</span>
</div>
这样一个纯CSS实现的文字滚动的效果就实现了,记录一下方便自己以后查找。
欢迎各位大佬指正