2015-10-15 73 views
4

我有一段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" }); 
}) 
+0

大括号!!!!你需要包装你的if语句的内容,否则它会在第一行后面出现 – Kaiido

+0

你错过了if和else中的'{}' –

+0

让我在这里阅读游行的雨......我经常有些惊讶对于某些可以说是解决问题的理由的upvotes的数量 - 基本的语法错误,对于未来的参考价值不大。一个好的提示可能是总是把你的代码通过一个验证器或者看看错误控制台。 – Shikkediel

回答

3

我看到你错过了梅开二度你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" }); 
} 
.... 
+0

谢谢,似乎很明显,但我想知道他们为什么没有在第一位置的括号把它给我...认为这很奇怪。 – steve0nz

+1

@ steve0nz因为你不需要它们,如果if(...)和else(...)之后只有一行, – Kaiido