当div在某个点上方滚动时改变文本的颜色

时间:2017-05-30 07:52:32

标签: javascript jquery

我希望当粉红色的div在浏览器窗口的底部上方完全滚动时,文本会改变颜色。当粉红色的div再次部分地滚动到浏览器窗口的底部边缘下方时,文本应该再次变为白色。

$(document).ready(function(){
  $(window).on('scroll' , function(){
    var WindowScrollTop = $(this).scrollTop(),
        Div_one_top = $('#one').offset().top,
        Div_one_height = $('#one').outerHeight(true),
        Window_height = $(this).outerHeight(true);
    if(WindowScrollTop >= (Div_one_top +  Div_one_height) - WindowScrollTop){
       $('#text1').css('color' , 'black');
    }else{
       $('#text1').css('color' , 'white');
    }
  }).scroll();
});
#one {
    height: 120vw;
    width: 100%;
    top: 0px;
    background-color: pink;
}

#text1 {
    width: 100%;
    font-size: 9em;
    margin-top: 100vw;
    position: absolute;
	  color:white;
}

#two {
    height: 50vw;
    width: 100%;
    top: 0px;
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one">
    <div id="text1">
        this is my text
    </div>
</div>
<div id="two">

</div>

1 个答案:

答案 0 :(得分:1)

需要比较Window_height和WindowScrollTop的总和:

$(document).ready(function(){
  $(window).on('scroll' , function(){
    var WindowScrollTop = $(this).scrollTop(),
        Div_one_top = $('#one').offset().top,
        Div_one_height = $('#one').outerHeight(true),
        Window_height = $(this).outerHeight(true);
    if(WindowScrollTop+Window_height >= (Div_one_top +  Div_one_height) ){
       $('#text1').css('color' , 'black');
    }else{
       $('#text1').css('color' , 'white');
    }
  }).scroll();
});
#one {
    height: 120vw;
    width: 100%;
    top: 0px;
    background-color: pink;
}

#text1 {
    width: 100%;
    font-size: 9em;
    margin-top: 100vw;
    position: absolute;
	  color:white;
}

#two {
    height: 50vw;
    width: 100%;
    top: 0px;
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one">
    <div id="text1">
        this is my text
    </div>
</div>
<div id="two">

</div>