[前端365]纯css实现滚动公告
关于
前端365:主要分享前端小技巧以及开发过程中的一些问题,欢迎关注+收藏+点赞,每天进步一点点。
最近在做项目时候需要做一个滚动公告,想了一下,纯css也是可以实现的,比js实现省事儿多了,最终效果如下。
实现过程
页面布局
-
首先写一下
html布局,一个大div包裹两个部分,左侧为公告小喇叭icon,右侧为文字内容区域,p标签设置超出部分隐藏,span标签做为真正滚动的标签。具体代码如下: -
html代码:
<div class='ad'>
<i class="iconfont"></i>
<p class='content'>
<span>重要通知:掘金创作者服务中心上线,速度过来体验一下吧! </span>
</p>
</div>
- css代码(采用了scss):
@font-face {
font-family: "iconfont"; /* Project id 2516453 */
src: url("//at.alicdn.com/t/font_2516453_g6qjhhqblt9.woff2?t=1620545333370")
format("woff2"),
url("//at.alicdn.com/t/font_2516453_g6qjhhqblt9.woff?t=1620545333370")
format("woff"),
url("//at.alicdn.com/t/font_2516453_g6qjhhqblt9.ttf?t=1620545333370")
format("truetype");
}
.iconfont {
font-family: "iconfont" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-webkit-text-stroke-width: 0.2px;
-moz-osx-font-smoothing: grayscale;
}
.ad {
width: 400px;
height: 60px;
background-color: #fff;
border-radius: 10px;
box-sizing: border-box;
padding: 0 20px;
display: flex;
align-items: center;
justify-content: flex-start;
font-size: 16px;
color: #353535;
box-shadow: 2px 1px 8px 1px rgb(228, 232, 235);
margin: 40px auto;
i {
color: #ff6146;
font-size: 20px;
margin-right: 10px;
}
.content{
flex: 1;
overflow: hidden;
span {
display: block;
width: auto;
white-space: nowrap;
}
}
}
添加animation动画
- 这里我们可以使用
animation配合transform来实现,让span标签x轴向左移动-100%:
@keyframes marquee {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
.content{
span{
animation: marquee 30s linear infinite;
}
}
- 效果预览
- 基本效果就出来了,但是每次滚动完成以后会迅速的执行下一次滚动,文字突然会出现在起始位置,滚动位置应该从最右边出来。我们可以给
span标签加padding来解决,让span元素滚动的更久一点,同时加一个hover效果,鼠标移入后滚动暂停。代码如下:
span {
display: block;
width: auto;
white-space: nowrap;
animation: marquee 30s linear infinite;
padding-left: 105%;
padding-right: 120%;
&:hover {
animation-play-state: paused;
}
- 最终效果如下图,也可以点击在线地址查看
结尾
👉关注前端365专栏:分享前端小技巧以及开发过程中的一些问题,欢迎关注+收藏+点赞,感谢支持~