import React, { useState, useEffect, useRef } from "react";
import "./autoCarousel.less";
const InfiniteScrollBox = ({ list }) => {
// console.log("🚀 ~ InfiniteScrollBox ~ list:", list);
const scrollContainerRef = useRef(null);
const [isHovering, setIsHovering] = useState(true);
const [scrollAmount, setScrollAmount] = useState(0);
const [speakerList, setSpeakerList] = React.useState(list);
const myList = [
{
color: "skyblue",
id: 1,
},
{
color: "skyblue",
id: 2,
},
{
color: "skyblue",
id: 3,
},
{
color: "skyblue",
id: 4,
},
{
color: "skyblue",
id: 5,
},
];
function splitArray(arr, chunkSize) {
const newArr = [];
if (arr.length <= 5) return [[arr]];
// 计算需要分割成几份
const chunkCount = Math.ceil(arr.length / chunkSize);
// console.log("🚀 ~ splitArray ~ chunkCount:", chunkCount);
Array(chunkCount)
.fill(0)
.map((item, index) => {
const arrItem = arr.slice(chunkSize * index, chunkSize * (index + 1));
if (arrItem.length < chunkSize) {
const fillItem = arr.slice(0, chunkSize - arrItem.length).reverse();
arrItem.push(...fillItem);
}
newArr.push(arrItem);
});
// console.log(1, arr);
return newArr;
}
// 设置定时器来自动滚动
useEffect(() => {
// console.log(splitArray(speakerList, 5));
let intervalId;
if (!isHovering) {
intervalId = setInterval(() => {
setScrollAmount((prev) => prev + 1); // 每次滚动1px
}, 30); // 设置滚动速度,这里是每10毫秒滚动1px
}
return () => clearInterval(intervalId);
}, [isHovering]);
// 添加滚动效果
useEffect(() => {
if (scrollContainerRef.current) {
const node = scrollContainerRef.current;
node.scrollLeft = scrollAmount;
// 判断是否滚动到最后一个盒子,如果是,将滚动位置重置
if (node.scrollWidth - node.scrollLeft === node.clientWidth) {
setScrollAmount(0); // 滚动到最开始
}
}
}, [scrollAmount]);
return (
<div
className="auto-carousel"
ref={scrollContainerRef}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
>
{myList.map((item, index) => (
<div className="scroll-box" key={item.id}>
{myList.map((item, index) => (
<div className="scroll-box-item" key={item.id}>
<div
className="scroll-box-item-img "
style={{
backgroundColor: item.color,
}}
/>
<p>中泰经济政策合作研究院</p>
</div>
))}
</div>
))}
</div>
);
};
export default InfiniteScrollBox;
/* 针对Webkit内核的浏览器 */
.auto-carousel::-webkit-scrollbar {
display: none;
/* 隐藏滚动条 */
}
/* 通用 */
.auto-carousel {
-ms-overflow-style: none;
/* IE和Edge */
overflow: -moz-scrollbars-none;
/* 旧版Firefox */
overflow: auto;
/* 启用滚动 */
}
/* 对于Firefox 64及以上版本 */
.auto-carousel {
scrollbar-width: none;
/* 隐藏滚动条 */
width: 100%;
height: 20rem;
white-space: nowrap;
overflow: hidden;
position: relative;
overflow-x: auto;
.scroll-box {
width: 81.25rem;
height: 12.5rem;
margin-right: 1.5rem;
display: inline-block;
.scroll-box-item {
margin-top: 3.8rem;
width: 15rem;
height: 10rem;
display: inline-block;
&:nth-child(even) {
margin: 0 1.5rem;
}
.scroll-box-item-img {
width: 15rem;
height: 10rem;
border-radius: .5rem;
display: inline-block;
}
p {
text-align: center;
margin-top: 1.5rem;
color: white;
}
}
}
}