【问题标题】:React JS sticky navigation onScrollReact JS 粘性导航 onScroll
【发布时间】:2017-09-22 18:22:55
【问题描述】:

我创建了一个 React 组件here,我试图在它滚动过去后让标题变得固定。在那种情况下,一切都按预期工作,但是在我滚动到元素高度之后,它会不断地打开和关闭类。

滚动功能如下:

handleScroll: function(event) {
  // Save the element we're wanting to scroll 
  var el = document.querySelector("#target");
  //  If  we've scrolled past the height of the element, add a class
  if (el.getBoundingClientRect().bottom <= 0) {
    console.log(el.getBoundingClientRect().bottom + " bottom");
    this.setState({
      headerIsActive: true
    });
    //  If we've scrolled back up to  the top of the container, remove the class
  } else if (el.getBoundingClientRect().top <= 0) {
    console.log(el.getBoundingClientRect().top <= 0 + " top");
    this.setState({
      headerIsActive: false
    });
  }
},

谁能告诉我我做错了什么?或者指出我正确的方向?

谢谢

【问题讨论】:

    标签: javascript reactjs scroll header fixed


    【解决方案1】:

    通过检测 window.scrollY 位置何时为 0 来修复,如下所示:

    handleScroll: function(event) {
      // Save the element we're wanting to scroll 
      var el = document.querySelector("#target");
      var pageY = window.scrollY
      //  If  we've scrolled past the height of the element, add a class
      if (el.getBoundingClientRect().bottom <= 0) {
        console.log(el.getBoundingClientRect().bottom + " bottom");
        this.setState({
          headerIsActive: true
        });
        //  If we've scrolled back up to  the top of the container, remove the class
      } else if (pageY == 0) {
        console.log("at top");
        this.setState({
          headerIsActive: false
        });
      }
    },
    

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 2022-01-18
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多