如何改变颜色时,用户滚动

How to change color when user scrolls

本文关键字:用户 滚动 何改 变颜色      更新时间:2023-09-26

我有一段jQuery代码,当用户向下滚动时,它会改变几个颜色的元素。但是当用户向上滚动页面时,我想切换到原始颜色。它不像我期望的那样工作…

原始代码

jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
})

修改后的代码也可以工作

})(window.jQuery);
jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
        jQuery(".primary-menu a").css({ color: "white" });
})

添加额外的css修饰符到第一个if语句终止脚本

})(window.jQuery);
jQuery(window).scroll(function() 
{
    var scrollTop = jQuery(this).scrollTop(),
    offset = jQuery('#masthead').height() - 55;
    if ( scrollTop < offset ) 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
        jQuery(".primary-menu a").css({ color: "black" });
    else 
        jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
        jQuery(".primary-menu a").css({ color: "white" });
})

我看到您在ifelse中缺少大括号。因此,只执行ifelse后面的第一行。而是添加一个括号,像这样:

 .....
 if ( scrollTop < offset ) {
      jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0)" });
      jQuery(".primary-menu a").css({ color: "black" });
 }
else {
     jQuery(".float-manu").css({ backgroundColor: "rgba(0,0,0,0.7)" });
     jQuery(".primary-menu a").css({ color: "white" });
 }
 ....