[英]Force scroll down to a particular point after some user scrolling [React]
[英]How to display a header only after the user starts to scroll down? [React]
我正在使用react,并且仅在用户在页面上向下滚动150px后才显示标题。
因此,当用户开始向下滚动时,我希望出现一个粘性标题。 再次,当用户滚动到页面顶部时,粘性标题消失。
<div className="container">
// display this on top of the page:
<JumbotronImage />
// display this when user starts to scroll, sticky on top of the page
<StickyHeader />
</div>
我试图用window.addEventListener('scroll'...来做到这一点,我也尝试了https://github.com/fisshy/react-scroll,但是还不能使它工作。有什么建议吗?
我可以认为您的代码如下所示。 解决方案应该像这样。
export class App extends React.Component {
componentDidMount() {
ReactDOM.findDOMNode(this.stickyHeader).addEventListener('scroll', this.handleScroll.bind(this));
}
componentWillUnmount() {
ReactDOM.findDOMNode(this.stickyHeader).removeEventListener('scroll', this.handleScroll.bind(this));
}
handleScroll() {
// Add the logic here
}
render() {
const {props} = this;
return (
<div className="container">
// display this on top of the page:
<JumbotronImage />
// display this when user starts to scroll, sticky on top of the page
<StickyHeader ref = {ele => this.stickyHeader = ele} />
</div>
);
}
}
您可以参考对我有用的这篇文章http://blog.sodhanalibrary.com/2016/07/detect-scroll-direction-using-reactjs.html#.Wo0hq0nTS-4在handleScroll中添加逻辑。
我通常将此脚本用于id =“ sticky”标题的粘性标题
$(window).scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos) {
//#sticky put your element for which you want it to apply
$('#sticky').addClass('stickyMenu');
} else {
$('#sticky').removeClass('stickyMenu');
}
});
为附加的类添加CSS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.