2014-06-18 37 views
-1

我遇到這些問題。 我希望身體根據溫度改變顏色。 它運作良好,但它只是最後一種被認爲是'#e74c3c'的顏色。 例如,它是15度,我得到紅色'#e74c3c'那麼它不是30°。溫度條件

if(weather.temp > 0) { 
$('body').animate({backgroundColor: '#3498db'}, 1500); 
} else { 
$('body').animate({backgroundColor: '#3498db'}, 1500); 
} 

if(weather.temp > 10) { 
$('body').animate({backgroundColor: '#f1c40f'}, 1500); 
} else { 
$('body').animate({backgroundColor: '#f1c40f'}, 1500); 
} 

if(weather.temp > 20) { 
$('body').animate({backgroundColor: '#f39c12'}, 1500); 
} else { 
$('body').animate({backgroundColor: '#f39c12'}, 1500); 
} 

if(weather.temp > 30) { 
$('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} else { 
$('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} 
+1

因爲您的最終else會被<= 30的任何東西觸發。您應該使用一個if和其他ifs。 – j08691

+1

看看你的代碼中的邏輯。每條if語句的每個子句中都有相同的顏色。當它到達最終的if語句時,它將背景顏色設置爲#e74c3c,而不管它是什麼。 – ElGavilan

+0

如果'weather.temp <= 0'會發生什麼? – JLewkovich

回答

2

因爲你最終都不會被觸發任何< = 30,您應該使用一個,如果和其他幾個IFS之後。

if (weather.temp <= 10) { 
    $('body').animate({ 
     backgroundColor: '#3498db' 
    }, 1500); 
} else if (weather.temp > 10 && weather.temp <= 20) { 
    $('body').animate({ 
     backgroundColor: '#f1c40f' 
    }, 1500); 
} else if (weather.temp > 20 && weather.temp <= 30) { 
    $('body').animate({ 
     backgroundColor: '#f39c12' 
    }, 1500); 
} else if (weather.temp > 30) { 
    $('body').animate({ 
     backgroundColor: '#e74c3c' 
    }, 1500); 
} 
+0

工作感謝您的幫助 –

+0

不客氣。 – j08691

0

它看起來就像動畫顏色#f1c40f,但隨後經歷到,如果20度和30度的語句並執行該動畫的身體不管是30多度或不else語句。

試試這個:

if (temp <= 10) 
    //animate body 
else if(> 10) 
    //animate body 
else if(> 20) 
    //animate body 
else if(> 30) 
    //animate body 
1

當執行到這一點:

if(weather.temp > 30) { 
$('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} else { 
$('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} 

將背景色設置爲#e74c3c或........#e74c3c。

鏈接這些結合在一起使用別人會給你想要的結果:

if (weather.temp <= 10) { 
    $('body').animate({backgroundColor: '#3498db'}, 1500); 
} else if (weather.temp > 10 && weather.temp <= 20) { 
    $('body').animate({backgroundColor: '#f1c40f'}, 1500); 
} else if (weather.temp > 20 && weather.temp <= 30) { 
    $('body').animate({backgroundColor: '#f39c12'}, 1500); 
} else if (weather.temp > 30) { 
    $('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} 
1
if(weather.temp >= 0 && weather.temp <= 10) { 
    $('body').animate({backgroundColor: '#3498db'}, 1500); 
} else if(weather.temp > 10 && weather.temp <= 20) { 
    $('body').animate({backgroundColor: '#f1c40f'}, 1500); 
} else if(weather.temp > 20 && weather.temp <= 30) { 
    $('body').animate({backgroundColor: '#f39c12'}, 1500); 
} else if(weather.temp > 30) { 
    $('body').animate({backgroundColor: '#e74c3c'}, 1500); 
} 

你必須把的weather.temp >= 0下限上你的第一個如果,否則負溫度將觸發顏色,這ISN是原始規格的一部分。如果您確實想要負溫度來觸發顏色,請刪除該條款。