使用Dom元素的animate实现无限滚动列表

一、需求

实现一个内容重复滚动的列表,鼠标hover时滚动停止,鼠标移走,继续滚动

二、实现逻辑与代码

这个需求用到了一个dom API(animate),这个方法可以用来做过渡动画、关键帧动画,接收两个参数

  • 关键帧:它可以是数组或者对象,数组内包裹的必须是对象,对象里的属性就是css属性和值了

  • 动画属性设置:常见的属性有以下:

    • duration:动画时长(单位毫秒)
    • Iterations:重复次数(默认1),无限循环:Infinity
    • fill:结束时是否复位,默认复位,不复位:forwards
    • delay:设置动画延迟时长(非必填)
    • easing:设置动画,运动速率,默认ease(慢-块-慢),linear:匀速。ease-in:慢-匀速,ease-in-out:慢-匀速-慢] [非必须]

MDN文档:animate

学习了这个api后,就可以来实现无限滚动列表需求了

demo代码如下:

// index.jsx

import React, { createRef, Component } from 'react';
import './index.css';

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

class RollList extends Component {
  constructor(props) {
    super(props)
    this.ref1 = createRef();
    this.ref2 = createRef();
    this.animate1 = null;
    this.animate2 = null;
  }


  componentDidMount() {
    const height = this.ref1.current.clientHeight;
    this.animate1 = this.ref1.current.animate([{ transform: 'translateY(0)' }, { transform: `translateY(-${height}px)` }], { duration: 4000, iterations: Infinity })
    this.animate2 = this.ref2.current.animate([{ transform: `translateY(${height}px)` }, { transform: 'translateY(0)' }], { duration: 4000, iterations: Infinity })
  }

  onMouseOver = () => {
    this.animate1.pause();
    this.animate2.pause();
  }

  onMouseOut = () => {
    this.animate1.play();
    this.animate2.play();
  }


  render() {
    return (
      <div className='boxOut'>
        <div className='box' ref={this.ref1}>
          {arr.map(item => (
            <div className='items'>{item}</div>
          ))}
        </div>
        <div className='box' ref={this.ref2}>
          {arr.map(item => (
            <div className='items'>{item}</div>
          ))}
        </div>
      </div>
    )
  }
}

export default RollList;
===================================================================================
// index.css
.boxOut {
  width: 600px;
  height: 300px;
  background: yellowgreen;
  overflow: hidden;
  position: relative;
}

.items {
  width: 600px;
  height: 40px;
}

.box {
  position: absolute;
}

Demo效果图:
在这里插入图片描述

三、总结

这里做个简单记录,这个dom API平时很少用,这次用了发现还是挺好用的;有兴趣的同学也可以深入学习下,应该也可做较为复杂的动画;

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ronychen’s blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值