2016-11-12 20 views
0

スクロールでクラスを追加するとこの問題が発生しました。これは私の元のスクリプトでした。スクロールでjsスクロールが動作しない

$(window).scroll(function(){ 
if ($(this).scrollTop() > 100) { 
    $('.navbar').addClass('navbar-inverse'); 
} else{ 
    $('.navbar').removeClass('navbar-inverse'); 
}}); 

ページがスクロールダウンしてサイトをリフレッシュしたときにこれが機能しませんでした。私は "else"を削除し、追加の "IF"を追加して解決しました。これが作業スクリプトです。

$(window).scroll(function(){ 
if ($(this).scrollTop() > 100) { 
    $('.navbar').addClass('navbar-inverse'); 
} if ($(this).scrollTop() < 100) { 
    $('.navbar').removeClass('navbar-inverse'); 
}}); 

今、私はそれの背後にある論理をあまり理解していません。最初のスクリプトが正しく動作しないのはなぜですか?

答えて

0

私はあなたのためにこれを書いています。その位置にオフセットを付けてから上を使うことができます。お役に立てれば :)。

$(document).ready(function(){ 
 

 
$(window).scroll(function(){ 
 
\t var paragraphPosition = $("#id1").offset(); 
 

 
\t var windowPostion = $(window).scrollTop(); 
 

 
\t if(paragraphPosition.top < windowPostion + 250){ 
 
\t \t $("#id1").addClass("navbar-inverse"); 
 
\t } 
 
\t else if(paragraphPosition.top > windowPostion){ 
 
\t \t $("#id1").removeClass("navbar-inverse"); 
 
\t } 
 
}); 
 

 
});
.box{ 
 
\t height: 200px; 
 
\t width: 300px; 
 
\t border: 2px solid #000000; 
 
} 
 
.navbar-inverse{ 
 
\t background: red; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<div class = "box"> 
 
\t Do greatest at in learning steepest. Breakfast extremity suffering one who all otherwise suspected. He at no nothing forbade up moments. Wholly uneasy at missed be of pretty whence. John way sir high than law who week. Surrounded prosperous introduced it if is up dispatched. Improved so strictly produced answered elegance is. 
 
</div> 
 
<div class = "box"> 
 
\t Do greatest at in learning steepest. Breakfast extremity suffering one who all otherwise suspected. He at no nothing forbade up moments. Wholly uneasy at missed be of pretty whence. John way sir high than law who week. Surrounded prosperous introduced it if is up dispatched. Improved so strictly produced answered elegance is. 
 
</div> 
 
<div id = "id1">This is a paragraph</div> 
 
<div class = "box"> 
 
\t Do greatest at in learning steepest. Breakfast extremity suffering one who all otherwise suspected. He at no nothing forbade up moments. Wholly uneasy at missed be of pretty whence. John way sir high than law who week. Surrounded prosperous introduced it if is up dispatched. Improved so strictly produced answered elegance is. 
 
</div> 
 
<div class = "box"> 
 
\t Do greatest at in learning steepest. Breakfast extremity suffering one who all otherwise suspected. He at no nothing forbade up moments. Wholly uneasy at missed be of pretty whence. John way sir high than law who week. Surrounded prosperous introduced it if is up dispatched. Improved so strictly produced answered elegance is. 
 
</div>

関連する問題