纯 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 表示无限次
相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
柴柴的小记8 小时前
前端vue引入特殊字体不生效
前端·javascript·vue.js
柠檬豆腐脑9 小时前
从前端到全栈:新闻管理系统及多个应用端展示
前端·全栈
bin91539 小时前
DeepSeek 助力 Vue 开发:打造丝滑的颜色选择器(Color Picker)
前端·javascript·vue.js·ecmascript·deepseek