jQueryを使用してユーザーが上から異なる距離にあるときにクラスを削除/追加したいとします。jQueryを使用して異なる高さでクラスを追加および削除する
私は正常に処理していますが、うまくいきますが、間違っていると思います。コードを最適化するために助けてください。
htmlは基本的にセクション(ヘッダーを含む)は100%幅です。さまざまな色。最初のセクション(審美的な目的のため)の上にヘッダーの色を変えたい。 また、ページが1ピクセルを超えてスクロールされているときに、影が欲しいと思っています。
私はクラスを追加/削除しています。
big else else if文を使用すると、条件が一致するたびにjsが他の一致をチェックしなくなるため、必要なすべてのクラスが適用されないため、うまく動作しません。
次のコードは動作しますが、私が言ったように、最適ではないと思います。ここ は、HTMLマークアップです:
<header class="dark no-shadow">
Header
</header>
<section class="blue">
Please Scroll Down to see the header changes...
</section>
<section>
The header color Should change when you pass through me.
</section>
そしてここでは、jQueryのコードです:(!私のような)
var header = $('header'),
blueSection = $('section.blue'),
// Calculate when to change the color.
offset = blueSection.offset().top + blueSection.height() - header.height();
$(window).scroll(function(){
var scroll = $(window).scrollTop();
// Remove Class "dark" after scrolling over the dark section
if (scroll >= offset) {
header.removeClass('dark');
} else {
header.addClass('dark');
}
// Remove Class "no-shadows" whenever not on the top of the page.
if (scroll >= 1) {
header.removeClass('no-shadow');
} else {
header.addClass('no-shadow');
}
});
そしてjsfiddle使用したい人のために: https://jsfiddle.net/shock/wztdt077/6/
おかげさまで先生!
どこかでスクロールした後にアクションを実行する方法を確認する - http://stackoverflow.com/questions/25660289/show-hide-div-when-passed-the-other-div/25661103#25661103 - あなたdivの位置やピクセルでこれを行うことができます – Tasos
デモがconentのコードを上から使用しています - https://jsfiddle.net/tgaoyx4b/ – Tasos
これはhttp://codereview.stackexchange.com/ – xpy