React JS粘性导航onscroll



我在这里创建了一个反应组件,我试图使标头自行滚动后固定。在这种情况下,一切都按预期工作,但是在我滚动过元素的高度之后,它会不断开关。

这是滚动功能:

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
    });
  }
},

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

谢谢

通过检测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
    });
  }
},

相关内容

  • 没有找到相关文章

最新更新