使用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.jsximport 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平时很少用,这次用了发现还是挺好用的;有兴趣的同学也可以深入学习下,应该也可做较为复杂的动画;