2017-04-25 149 views
1

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

这里的滚动功能:

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

通过在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 
    }); 
    } 
}, 
0

你的要求几乎有同样的想法,因为这反应库,它是由我之前创建: https://github.com/thinhvo0108/react-sticky-dynamic-header

随意玩它,虽然很简单!

或者你可以签出源代码,看看我是如何处理的滚动位置和头的高度(反应粘性动力头/ src目录/ index.js)

PS:我的图书馆甚至会超出你的预期(不仅仅是“在它自己滚动后自动修复”),你可以实际使用2个不同的组件(或DOM元素),而不管它的大小是否为头部的外观(在粘性之前和之后当用户向下滚动&)。另外,当标题交换时,也会显示一些平滑的效果。