方法一:
直接使position:sticky属性即可。
<div className="scroller-fixed"></div>
.scroller-fixed {
position:sticky;
top: 0;
}
方法二:
监听scroll时间,当吸顶块滑至顶部时,为该吸顶块添加新的类名,通过给新类设置css样式实现(position: fixed)。但这种方法在ios中有问题,因为ios手机对scroll的触发做了限制(只有在滚动停止时才触发),导致吸顶效果延迟。
import cs from 'classnames';
constructor(props) {
super(props);
this.state = {
navTop: false,
};
this.$tab = null;
this.offsetTop = 0;
}
componentDidMount() {
this.$tab = this.refs.tab;
if (this.$tab) {
this.offsetTop = this.$tab.offsetTop;
window.addEventListener('scroll', this.handleScroll.bind(this));
}
}
handleScroll() {
let sTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
if (!this.state.navTop && sTop >= this.offsetTop) {
this.setState({
navTop: true,
});
}
if (sTop < this.offsetTop) {
this.setState({
navTop: false,
});
}
}
<div ref="tab" className={cs({'scroller-fixed': this.state.navTop})}></div>
网友评论