我刚刚在滚动中添加了一个类来解决这个问题。这是我原来的剧本。
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.navbar').addClass('navbar-inverse');
} else{
$('.navbar').removeClass('navbar-inverse');
}});
当页面一直向下滚动并且刷新网站时,这没有用。我通过删除" else"解决了这个问题。并添加aditional" IF"。这是工作脚本。
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.navbar').addClass('navbar-inverse');
} if ($(this).scrollTop() < 100) {
$('.navbar').removeClass('navbar-inverse');
}});
现在我不太了解它背后的逻辑。为什么第一个脚本无法正常工作?
答案 0 :(得分:0)
我刚给你写了这个。您可以使用偏移,然后使用顶部作为位置。希望这有助于:)。
$(document).ready(function(){
$(window).scroll(function(){
var paragraphPosition = $("#id1").offset();
var windowPostion = $(window).scrollTop();
if(paragraphPosition.top < windowPostion + 250){
$("#id1").addClass("navbar-inverse");
}
else if(paragraphPosition.top > windowPostion){
$("#id1").removeClass("navbar-inverse");
}
});
});
.box{
height: 200px;
width: 300px;
border: 2px solid #000000;
}
.navbar-inverse{
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class = "box">
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">
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">
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">
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>