js: change style based in scroll position

久未见 提交于 2019-12-13 03:35:29

问题


I have this code to change the background color of an element (which works fine)

<script>
window.onscroll = function() {
    if(document.body.scrollTop == 0) {
       jQuery("header#main-header").css('background-color', 'red');
    }
}
</script>

Problem is that I need to set the color to red only if the page scroll is between 0 and 100 and set the color to yellow if is bigger than 100.

I tried this in this page: http://temporal-1.d246.dinaserver.com/ but not working:

<script>
window.onscroll = function() {
    if(document.body.scrollTop <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    if(document.body.scrollTop >= 100) {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
}
</script>

回答1:


Well you need to calculate top offset a little differently

window.onscroll = function() {
    var doc = document.documentElement;
    var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
    if(top <= 99) {
       jQuery("header#main-header").css('background-color', 'red');
    }
    else {
       jQuery("header#main-header").css('background-color', 'yellow');
    }
} 



回答2:


jQuery(document).ready(function(){
jQuery("body").css('background-color', 'red');
jQuery(window).scroll(function(){
    if ( jQuery(document).scrollTop() <= 99 ) {
         jQuery("body").css('background-color', 'red');
    } else {
        jQuery("body").css('background-color', 'yellow');
    }
})

})




回答3:


A simple execution for changing an element when you scroll

$(function () {
    $(document).scroll(function() {
        var $nav = $("class name");
        // $nav.height() can be changed to whatever height you want to start the change effect
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height()); 
    });
});


来源:https://stackoverflow.com/questions/48785568/js-change-style-based-in-scroll-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!