react实现bilibili的侧边屏幕滚动导航
程序员文章站
2022-05-24 22:07:27
...
react实现类似于bilibili的右侧导航栏的功能,功能点:
- 点击定位到指定位置
- 监听滚动,滚动到指定位置,改变导航颜色
import React, { Component } from 'react';
import classNames from 'classnames';
require('./index.less')
const navArr = [
'推荐','JK','Lo','汉服','Coser','动漫','手绘','小说'
]
class HomePage extends Component {
constructor(props){
super(props)
this.state = {
currentId:0
}
}
componentWillMount(){
/**
* 获取当前位置;获取当前位置
*/
var _this = this;
//监听屏幕滚动
window.onscroll = function(){
//获取当前滚动条的位置
var top = document.documentElement.scrollTop;
var sections = document.getElementById("center-con").getElementsByClassName("section");
//存放当前位置的id;即顺序
var currentId;
for (var i =0; i<sections.length; i++) {
var itemTop = sections[i].offsetTop;
//当前元素顶部相对于指定元素顶部的偏移
if(top>itemTop-50){
currentId = i;
}else{
break;
}
}
_this.setState({currentId:currentId})
}
}
//实现点击导航跳转到指定位置
scrollToAnchor = (anchorId) => {
if (anchorId) { // 找到锚点 id
let anchorElement = document.getElementById(anchorId);
if(anchorElement) { // 如果对应id的锚点存在,就跳转到锚点
anchorElement.scrollIntoView({block: 'start', behavior: 'smooth'});
}
}
}
render() {
const content = (
<div className="home-con" >
//内容部分
<div className="main-con" >
<div className="center-con" id="center-con">
<div className="section" id="nav-0"> </div>
<div className="section" id="nav-1"></div>
<div className="section" id="nav-2"></div>
<div className="section" id="nav-3"></div>
<div className="section" id="nav-4"></div>
<div className="section" id="nav-5"></div>
<div className="section" id="nav-6"></div>
<div className="section" id="nav-7"></div>
</div>
</div>
//导航部分
<div className="nav-con" id="menu">
{navArr.map((item,index)=>{
return <a className={classNames("nav-item",[this.state.currentId===index&&"nav-item-active"])} onClick={this.scrollToAnchor.bind(this,'nav-'+index)}>{item}</a>
})}
</div>
</div>
)
return (
<BasicLayout content={content}/>
);
}
}
export default HomePage;
监听屏幕改变导航思路:
- 获取滚动条滚动高度
- 计算每个内容元素相对于顶部偏移,对比,获取元素index,修改
上一篇: 实现自己的DialogBuilder封装:大小、显示位置和动画
下一篇: MySql数据类型