簡體   English   中英

僅在用戶開始向下滾動后如何顯示標題? [反應]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM