纯 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 表示无限次
相关推荐
小小小小宇31 分钟前
TS泛型笔记
前端
小小小小宇36 分钟前
前端canvas手动实现复杂动画示例
前端
codingandsleeping37 分钟前
重读《你不知道的JavaScript》(上)- 作用域和闭包
前端·javascript
小小小小宇1 小时前
前端PerformanceObserver使用
前端
charlee442 小时前
给Markdown渲染网页增加一个目录组件(Vite+Vditor+Handlebars)(下)
css·markdown·响应式设计·flexbox·粘性定位
zhangxingchao2 小时前
Flutter中的页面跳转
前端
烛阴3 小时前
Puppeteer入门指南:掌控浏览器,开启自动化新时代
前端·javascript
全宝3 小时前
🖲️一行代码实现鼠标换肤
前端·css·html
小小小小宇4 小时前
前端模拟一个setTimeout
前端
萌萌哒草头将军4 小时前
🚀🚀🚀 不要只知道 Vite 了,可以看看 Farm ,Rust 编写的快速且一致的打包工具
前端·vue.js·react.js