2017-04-25 10 views
1

Reactコンポーネントhereを作成しました。ヘッダーをスクロールした後に修正しようとしています。そのインスタンスではすべてが期待どおりに機能しますが、要素の高さをスクロールした後は、クラスを常にオンとオフに切り替えます。React JS sticky navigation 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 
    }); 
    } 
}, 

誰かが私が間違ってやっているものを私に教えてくださいことはできますか?または、正しい方向に私を向ける?

おかげ

答えて

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要素)をヘッダーの外観(スティッキーの前後)に関係なく実際に使用することができますユーザーが&を上にスクロールしたとき)。また、ヘッダーがインターチェンジすると、スムーズなエフェクトも表示されます。

関連する問題