纯 CSS 实现 超长内容滚动播放。

需求:文案来回在指定区域内水平滚动,并且在头尾处停留一段时间 ​

以vue为例,封装一个通用组件

javascript 复制代码
<template>
  <view class="box">
    <view class="scroll-wrap">
      <view class="scroll-item" :style="{color:color,fontWeight:fontWeight, fontSize:`${fontSize}rpx`}">
        {{ text}}
      </view>
    </view>
  </view>
</template>

<script>
  // 使用需要外层套一个div给盒子宽度
  export default {
    props: {
      // 滚动的文本
      text: {
        type: String,
        default: '',
      },
      // 颜色
      color: {
        type: String,
        default: '#333333',
      },
      // 文字大小
      fontSize: {
        type: String,
        default: '24',
      },
      fontWeight: {
        type: String,
        default: '500',
      }
    },
    data() {
      return {};
    },
    mounted() {},
    methods: {},
  };
</script>

<style lang="scss" scoped>
  .box {
    width: 100%;
    // border: 1px solid;
  }

  .scroll-wrap {
    max-width: 100%;
    display: inline-block;
    vertical-align: top;
    overflow: hidden;
    white-space: nowrap;

  }

  .scroll-item {

    animation: scroll linear 4s alternate infinite;
    float: left;
  }

  @keyframes scroll {
    0% {
      margin-left: 0;
      transform: translateX(0);
    }

    10% {
      margin-left: 0;
      transform: translateX(0);
    }

    90% {
      margin-left: 100%;
      transform: translateX(-100%);
    }

    100% {
      margin-left: 100%;
      transform: translateX(-100%);
    }
  }
</style>

使用组件

javascript 复制代码
<view style="width:200rpx;">
  <text-scroll :text="我很长啊我很长啊我很长啊我很长啊我很长啊" fontSize="32" fontWeight="600"></text-scroll>
</view>

简单解释一下当前 animation 的属性

  • animation-name:所使用的 @keyframes 的名称 scroll
  • animation-timing-function:动画的速度曲线,linear 表示匀速
  • animation-duration:规定完成动画所花费的时间为 4s
  • animation-direction:是否应该轮流反向播放动画,alternate 表示在偶数次会反向播放
  • animation-iteration-count:定义动画的播放次数,infinite 表示无限次
相关推荐
Freedom风间4 小时前
前端优秀编码技巧
前端·javascript·代码规范
萌萌哒草头将军4 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军4 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm
拉不动的猪5 小时前
SDK与API简单对比
前端·javascript·面试
runnerdancer5 小时前
微信小程序蓝牙通信开发之分包传输通信协议开发
前端
山海上的风5 小时前
Vue里面elementUi-aside 和el-main不垂直排列
前端·vue.js·elementui
电商api接口开发5 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
亭台烟雨中5 小时前
【前端记事】关于electron的入门使用
前端·javascript·electron