在Scroll上反应JS粘性导航

时间:2017-04-25 16:02:53

标签: javascript reactjs scroll header fixed

我已经创建了一个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
    });
  }
},

有人可以告诉我我做错了什么吗?还是指出我正确的方向?

由于

1 个答案:

答案 0 :(得分: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
    });
  }
},