react 超出高度自动滚动组件
react 超出高度自动滚动组件 鼠标放入暂停 鼠标放出自动滚动
·
import { useEffect, useRef } from 'react';
export interface ScrollProps {
/** 根类名 */
className?: string;
children?: any;
style?:any;
}
const Scroll: React.FC<ScrollProps> = ({ className, children,style }) => {
let timeoutTimer: NodeJS.Timeout;
let intervalTimer: NodeJS.Timer;
const scrollDomRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (scrollDomRef.current) {
// 开始滚动
autoScroll();
// 鼠标移入,清除滚动
scrollDomRef.current.onmouseenter = () => {
window.clearInterval(intervalTimer);
window.clearTimeout(timeoutTimer);
};
// 鼠标离开,重新滚动
scrollDomRef.current.onmouseleave = () => {
autoScroll();
};
}
}, [scrollDomRef]);
const autoScroll = () => {
if (timeoutTimer) {
window.clearTimeout(timeoutTimer);
}
timeoutTimer = setTimeout(() => {
const clientH = scrollDomRef.current?.clientHeight || 0;
const scrollH = scrollDomRef.current?.scrollHeight || 0;
if (intervalTimer) {
window.clearInterval(intervalTimer);
}
// 无滚动
if (scrollH == clientH) return;
intervalTimer = setInterval(() => {
if (scrollDomRef.current) {
const scrollTop = scrollDomRef.current.scrollTop;
const distance = scrollH - clientH;
// 计算滚动距离
if (scrollTop >= distance - 1) {
// 滚动距离大于可滚动高度时,回到顶部
scrollDomRef.current.scrollTop = -1;
console.log('重新循环');
window.clearInterval(intervalTimer);
autoScroll();
}
scrollDomRef.current.scrollTop += 2;
}
}, 80);
}, 3000);
};
return (
<div ref={scrollDomRef} className={`${className}`} style={style}>
{children}
</div>
);
};
export default Scroll;
例子:
更多推荐
已为社区贡献2条内容
所有评论(0)