代码
export default class FixedHeader extends React.Component {
constructor(props) {
super(props);
this.state = { needFixed: false };
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
handleScroll = event => {
// 滚动条滚动高度
const scrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
console.log(scrollTop);
const fixedTop = document.getElementById('components1').offsetTop;
if (scrollTop >= fixedTop) {
this.setState({ needFixed: true });
console.log({ needFixed: true });
} else if (scrollTop < fixedTop) {
this.setState({ needFixed: false });
console.log({ needFixed: false });
}
};
render() {
const { needFixed } = this.state;
const anchorHeaderStyle = needFixed ? { position: 'fixed', top: 0, zIndex: 9 } : {};
return (
<PageLayout>
<div>此处为页面的其他部分元素,反正很多<div>
<div className={styles.anchorHeader} id="anchorHeader" style={anchorHeaderStyle}>
<div className={styles.anchorContent}>
<Anchor>
<Link href="#components1" title="典型业务场景" />
<Link href="#components2" title="应用案例" />
</Anchor>
</div>
</div>
<div className={styles.content} id="components1">典型业务场景</div>
<div className={styles.content} id="components1">客户案例</div>
</PageLayout>
);
}
}
实现效果
由于使用的antd的组件,对antd组件的样式进行改造
原来的Anchor锚点组件
显然不符合我的需要,故根据业务需求进行修改为横向的
.anchorHeader {
margin: 0 auto;
width: 100%;
background-color: #fff;
}
.anchorContent {
margin: 0 auto;
min-width: 255px;
max-width: 255px;
}
.anchorContent :global(.ant-anchor-link) {
padding: 7px 0 7px 16px;
line-height: 1.143;
display: inline-block;
}
.anchorContent :global(.ant-anchor) {
box-sizing: border-box;
margin: 0;
padding: 0;
color: rgba(0, 0, 0, 0.65);
font-size: 25px;
font-variant: tabular-nums;
line-height: 1.5;
list-style: none;
font-feature-settings: 'tnum';
position: relative;
padding-left: 2px;
}
.anchorContent :global(.ant-anchor-wrapper) {
margin-left: -4px;
padding-left: 4px;
overflow: auto;
background-color: #fff;
height: 50px;
}
.anchorContent :global(.ant-anchor-ink) {
position: absolute;
top: 0;
left: 0;
height: 100%;
display: none;
}
.anchorContent :global(.ant-anchor-link > .ant-anchor-link-title) {
display: block;
padding-bottom: 3px;
border-bottom: 1px solid #faf3f5;
}
.anchorContent :global(.ant-anchor-link-active > .ant-anchor-link-title) {
color: #1890ff;
display: block;
padding-bottom: 3px;
border-bottom: 1px solid #1890ff;
}