新建scrollCarousel.ts文件,代码如下:
interface CarouselElements {outerContainer: HTMLDivElement;innerContainer: HTMLDivElement;interval: number;
}class ScrollCarousel {private outerContainer: HTMLDivElement;private innerContainer: HTMLDivElement;private scrollHeight: number;private autoScrollInterval: NodeJS.Timer | null;private interval: number;private scrollTop: number;constructor(elements: CarouselElements) {this.outerContainer = elements.outerContainer;this.innerContainer = elements.innerContainer;this.scrollHeight = this.outerContainer.scrollHeight;this.autoScrollInterval = null;this.scrollTop = 0;this.interval = elements.interval;// 绑定事件到此实例this.handleMouseEnter = this.handleMouseEnter.bind(this);this.handleMouseLeave = this.handleMouseLeave.bind(this);// 添加事件监听器this.outerContainer.addEventListener("mouseenter", this.handleMouseEnter);this.outerContainer.addEventListener("mouseleave", this.handleMouseLeave);// 开始滚动this.startAutoScroll();}startAutoScroll() {if (this.autoScrollInterval === null) {this.autoScrollInterval = setInterval(() => {this.scrollNext();}, this.interval);}}stopAutoScroll() {if (this.autoScrollInterval !== null) {clearInterval(this.autoScrollInterval);this.autoScrollInterval = null;}}private scrollNext() {if (this.scrollTop < this.scrollHeight - this.outerContainer.clientHeight) {this.scrollTop += 2;} else {this.scrollTop = 0;this.outerContainer.scrollTop = 0;}this.outerContainer.scrollTop = this.scrollTop;}private handleMouseEnter() {this.stopAutoScroll();}private handleMouseLeave() {this.startAutoScroll(); // Restart with the same interval}public destroyEventListener() {this.scrollTop = 0;this.outerContainer.scrollTop = 0;this.stopAutoScroll();this.outerContainer.removeEventListener("mouseenter", this.handleMouseEnter);this.outerContainer.removeEventListener("mouseleave", this.handleMouseLeave);}
}export default ScrollCarousel;
页面结构如下
<div class="winding-machine-wrap" id="csOuterDiv"><div class="list-wrap" id="csInnerDiv"></div>
</div>
在页面中调用
// 假设你有两个 div 元素作为容器
const xsOuterDiv = document.getElementById("xsOuterDiv") as HTMLDivElement;
const xsInnerDiv = document.getElementById("xsInnerDiv") as HTMLDivElement;
// 创建 ScrollCarousel 实例
if (xsOuterDiv && xsInnerDiv) {xsScrollCarousel = new ScrollCarousel({outerContainer: xsOuterDiv,innerContainer: xsInnerDiv,interval: 60});
}
最后别忘了销毁定时器
// 离开组件清除定时器
onBeforeUnmount(() => {// 清除自动滚动定时器xsScrollCarousel && xsScrollCarousel.destroyEventListener();
});