javascript - React JS 粘性导航 onScroll

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

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

谢谢

最佳答案

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

关于javascript - React JS 粘性导航 onScroll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615719/

相关文章:

reactjs - 将使用 react-router v5 完成的 BreadCrumb 组件更改为 react router v6

javascript - Reactjs : display time in 24hr format

jquery - 如何在 javascript 中设置滚动条处理程序?

ios - 具有水平和垂直分页的 UICollectionViewLayout

javascript - 如何使用 jQuery 动态添加链接到复选框或输入标记中的值

javascript - rxjs 有条件地先于另一个可观察值触发一个可观察值

javascript - 我应该将我的多个 css 文件压缩为一个用于我的 React js 应用程序吗?

javascript - 调整容器div的高度?

javascript - 在 JavaScript 和 JSON 中传递 Google 脚本值

javascript - 防止 SPACE 和 ARROW 滚动 [游戏 Iframe]