【问题标题】:How to display a header only after the user starts to scroll down? [React]如何仅在用户开始向下滚动后才显示标题? [反应]
【发布时间】:2018-02-21 16:48:03
【问题描述】:

我正在使用 react,我希望仅在用户在页面上向下滚动 150 像素后才显示标题。

所以当用户开始向下滚动时,我希望出现一个粘性标题。同样,当用户滚动到页面顶部时,粘性标题会消失。

<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 但无法使其正常工作。有什么建议吗?

【问题讨论】:

    标签: javascript html css reactjs


    【解决方案1】:

    我可以想到您的代码如下所示。解决方案应该是这样的。

    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 中添加逻辑。

    【讨论】:

      【解决方案2】:

      我通常将此脚本用于 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

      【讨论】:

        猜你喜欢
        • 2020-10-29
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        相关资源
        最近更新 更多