react 电梯导航,快速的实现页面滚动导航
一、实现思路
电梯导航主要是要实现两个功能点:
1. 左边导航,右边是对应的内容
2. 点击左边的导航,右边滚动页面到指定位置,反之右边滚动页面到指定位置,导航高亮
使用技术:
react less
1. scrollIntoView,让指定元素调用这个方法可以滚动到视图区
2. 防抖
3.scrollTop ;offsetHeight
二、开始
html
---左边的导航
<div className="left-menu" ref={leftRef}>
{industries.map((industry, index) => (
<div
key={index}
className={`menu-item ${leftActiveIndex === index ? 'active' : ''}`}
onClick={() => handleLeftClick(index)}
>
{industry}
</div>
))}
</div>
---右边的内容
<div className="right-content" ref={rightRef} id="content">
{industries2?.map((industry, index) => (
<div key={index} className="industry" id={`industry-${index}`}>
<h2>{industry?.name}</h2>
<div className='product-list'></div>
</div>
))}
</div>
------------------------------------------------------js
const leftRef = useRef(null);
const rightRef = useRef(null);
const [leftActiveIndex, setLeftActiveIndex] = useState(0);
useEffect(() => {
const rightElement = rightRef.current;
const debouncedHandleScroll = debounce(handleRightScroll, 20);
rightElement.addEventListener('scroll', debouncedHandleScroll);
return () => {
rightElement.removeEventListener('scroll', debouncedHandleScroll);
debouncedHandleScroll.cancel();
};
}, [leftActiveIndex]);
//点击导航
const handleLeftClick = (index) => {
setLeftActiveIndex(index)
const rightElement = rightRef?.current?.querySelectorAll('.industry')[index];
rightElement.scrollIntoView({ behavior: 'smooth' });
setTimeout(() => {
window.scrollBy(0, -topHeight); // 向上微调指定的像素数
}, 1);
};
// 左边页面滚动
const handleRightScroll = () => {
const scrollTop = rightRef?.current?.scrollTop;
let itemHeight = rightRef?.current?.children[leftActiveIndex]?.offsetHeight || 0;
const currentIndex = Math.floor(scrollTop / itemHeight);
const validIndex = Math.max(0, Math.min(currentIndex, industries?.length - 1));
setLeftActiveIndex(validIndex);
};
直接使用,无删版,欢迎你的访问