每当滚动在2 div之间时更改css [英] Change css whenever scroll is between 2 divs

查看:112
本文介绍了每当滚动在2 div之间时更改css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在#trigger-start#trigger-end之间的任何时候更改我的.products,我创建了这个jQuery文件,但是由于某些原因,它不能很好地工作.只要我启用了警报,警报就会起作用.

So I tried to change my .products whenever it was between #trigger-start and #trigger-end, I created this jQuery file but for some reason it doesn't work quite good. The alerts do work whenever I enable them tho.

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中设置样式)

And yes the 2 divs (trigger-start --end are placed in html and styled in css)

图片向您展示我的意思

Image to show you what I mean

小提琴

推荐答案

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

I will add a real demo to show how you can implement your code then change your code to this

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和Class或任何您想要的内容.

hope it works for you; You need to add your custom CSS and Class or whatever you want.

这篇关于每当滚动在2 div之间时更改css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆