const [isScrolle, setIsScrolle] = useState(true);
// 滚动速度,值越小,滚动越快
const speed = 30;
const warper = useRef();
const childDom1 = useRef();
const childDom2 = useRef();
const dataSource = [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区',
},
{
key: '3',
name: '胡彦斌',
age: 32,
address: '西湖区',
},
{
key: '4',
name: '胡彦祖',
age: 42,
address: '西湖区',
},
{
key: '5',
name: '胡彦斌',
age: 32,
address: '西湖区',
},
{
key: '6',
name: '胡彦祖',
age: 42,
address: '西湖区',
},
{
key: '7',
name: '胡彦斌',
age: 32,
address: '西湖区',
},
{
key: '8',
name: '胡彦祖',
age: 42,
address: '西湖区',
},
];
// 开始滚动
useEffect(() => {
// 多拷贝一层,让它无缝滚动
childDom2.current.innerHTML = childDom1.current.innerHTML;
let timer;
if (isScrolle) {
timer = setInterval(
() =>
warper.current.scrollTop >= childDom1.current.scrollHeight
? (warper.current.scrollTop = 0)
: warper.current.scrollTop++,
speed
);
}
return () => {
clearTimeout(timer);
};
}, [isScrolle]);
const hoverHandler = (flag) => setIsScrolle(flag);
<div className='parent' ref={warper}>
<div className='child' ref={childDom1}>
{dataSource.map((item) => (
<li
key={item}
onMouseOver={() => hoverHandler(false)}
onMouseLeave={() => hoverHandler(true)}
>
<span className='childBox'>{item.name}</span>
<span className='childBox'>{item.age}</span>
<span className='childBox'>{item.address}</span>
<span className='childBox'>{item.name}</span>
</li>
))}
</div>
<div className='child' ref={childDom2}></div>
</div>
css
.parent {
width: 100%;
height: 230px;
overflow-y: scroll;
scrollbar-width: none;
-ms-overflow-style: none;
}
.parent::-webkit-scrollbar {
display: none;
}
/*设置的子盒子高度大于父盒子,产生溢出效果*/
.child {
height: auto;
}
.child li {
height: 50px;
margin: 2px 0;
line-height:50px;
color:#3B3B3B;
display:flex;
// background: #009678;
.childBox{
width:107px;
text-align:center;
line-height:50px;
}
}
.child li:nth-of-type(odd){ background:#fff;}//奇数行
.child li:nth-of-type(even){ background:rgb(242,242,242);}//偶数行
实现效果: