2015-10-15 76 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