如上图,列表左右滚动轮播,用户鼠标移动到轮播区域,动画停止,鼠标移开轮播继续。
此例子实现技术框架是用的React+CSS。
主要用的是css的transform和transition来实现左右切换动画效果。
React代码:
import React, { useState, useRef, useEffect } from 'react';
import styles from './index.module.css';
export default function Swiper() {
const dataSource = [
'https://t7.baidu.com/it/u=1732966997,2981886582&fm=193&f=GIF',
'https://t7.baidu.com/it/u=1785207335,3397162108&fm=193&f=GIF',
'https://t7.baidu.com/it/u=3423293041,3900166648&fm=193&f=GIF',
'https://t7.baidu.com/it/u=3659156856,3928250034&fm=193&f=GIF',
'https://t7.baidu.com/it/u=826329656,2212580321&fm=193&f=GIF',
];
const [tabIndex, setTabIndex] = useState(0);
const [isScroll, setIsScroll] = useState(true);// 用于当鼠标移入时,轮播停止
const scrollerRef = useRef(null);
const timer = useRef(null);
useEffect(() => {
timer.current = setInterval(() => {
if (!isScroll) return;
const dom = scrollerRef.current;
if (dom && dom.style) {
const _tabIndex = tabIndex === dataSource.length - 1 ? 0 : tabIndex + 1;
const width = dom.children[tabIndex].clientWidth;
dom.style.transform = `translateX(${-tabIndex * width}px)`;
setTabIndex(_tabIndex);
}
}, 1 * 1000);
return () => {
timer.current && window.clearInterval(timer.current);
};
}, [isScroll, tabIndex, dataSource]);
return (
<div className={styles.container}>
<div
className={styles.wrapper}
ref={scrollerRef}
onMouseEnter={() => setIsScroll(false)}
onMouseLeave={() => setIsScroll(true)}
>
{dataSource.map((item, index) => (
<div className={styles.item} key={index}>
<img src={item} className={styles.image} alt={index} />
</div>
))}
</div>
</div>
);
}
Css :
.container {
height: 300px;
width: 500px;
overflow: hidden;
.wrapper {
transform: translate(0);
transition: transform 0.3s;
width: 100%;
display: flex;
.item {
flex: 0 0 100%;
height: 300px;
.image {
width: 100%;
height: 100%;
}
}
}
}