滚动在2个div之间时更改css

时间:2016-10-07 12:08:17

标签: javascript jquery html css

所以我尝试在.products#trigger-start之间更改我的#trigger-end,我创建了这个jQuery文件,但由于某种原因它不能很好地工作。每当我启用它们时,警报都会起作用。

的jQuery

var scrollFilter1 = $('#trigger-start').offset().top;
var scrollFilter2 = $('#trigger-end').offset().top;
var windowPosY = $(this).scrollTop();
$(window).scroll(function(){
    if(windowPosY >= scrollFilter1 && windowPosY <= scrollFilter2){
        //alert('yey');
        $('.products').css('opacity','0.6');
    } else {
        //alert('ney');
        $('.products').css('opacity','1');
    }
});

是的2个div(trigger-start --end放在html中并在css中设置样式)

图片向您展示我的意思 enter image description here

拨弄

fiddle

1 个答案:

答案 0 :(得分:1)

我将添加一个真实的演示,以展示如何实现代码,然后将代码更改为

var scrollFilter1 = $('#trigger-start').offset().top;
var scrollFilter2 = $('#trigger-end').offset().top;

var $w = $(window).scroll(function(){
    if ( $w.scrollTop() > scrollFilter1 && $w.scrollTop() < scrollFilter2 ) {  
        $('.products').addClass('bluebg');
    } else {
      $('.products').removeClass('bluebg');
    }
});
.products{
  background:red;
  position:fixed;
  width:200px;
  height:200px;
}
.bluebg{
 background:blue;
}
#sth-top{
  height:200px;
  width:400px;
    background:black;


}
#trigger-start{
    height:300px;
  width:400px;
     background:purple;
   
}
#sth-middle{
  height:200px;
  width:400px;
     background:black;
}

#trigger-end{
    height:300px;
  width:400px;
     background:purple;
}
#sth-bottom{
  height:200px;
  width:400px;
    background:black;


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="products"></div>
<div id="sth-top"></div>
<div id="trigger-start"></div>
<div id="sth-middle"></div>
<div id="trigger-end"></div>
<div id="sth-bottom"></div>

希望它适合你;您需要添加自定义CSS和类或任何您想要的。