2017-05-30 30 views
0

我希望在瀏覽器窗口的底部egde上方滾動粉紅色的div時,文本將更改顏色。當粉紅色的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; 
 
\t 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>

+0

如果你想改變文本的顏色爲什麼不只是做'$( '#text1').css('color','thecoloryouwant');' –

+0

坦克你和對不起@Carsten,我哈d在我的問題中出現代碼錯誤。這現在已經修復。但我的問題仍然存在。 Ik似乎在粉紅色div底部高於瀏覽器窗口底部邊緣的那一刻,文本不會改變顏色。 – Eddy

+0

函數$(this).scrollTop()從窗口頂部獲得滾動條,您必須使用$(window).height()添加窗口高度。 – iubema

回答

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; 
 
\t 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>

+0

謝謝你,@Michal!有用!!! – Eddy