2013-10-08 80 views
-1

我有一個粘滯的標題,在用戶向下滾動時停留在頁面的頂部。設置變量顯示爲'undefined'?

我想製作一個腳本,隱藏標題的菜單部分,如果用戶滾動過去某個點。我也想打,如果用戶點擊屏幕頂部的菜單重新出現,所以我寫了這個劇本:

var lastmargintop = 0; 

$(document).scroll(function() { 


var margintop = $('#stickyheader').css('marginTop'); 
var margintop = parseInt(margintop, 10); 

if(margintop > 10){ 
    $('#menu').hide('fast'); 
} 

if (lastmargintop < 10){ 
    $('#menu').show('fast'); 
} 

console.log(lastmargintop); 
var lastmargintop = margintop; 

}); 

但變量lastmargintop顯示爲undefined。我不知道爲什麼會這樣。誰能告訴我爲什麼?

+0

你意識到你的if語句是硬編碼來說'if(0 <10)'?嘗試把'console.log'調用**在** var lastmargintop = ...行 –

+0

@scrowler哎呀抱歉,這並不意味着在函數內 – MeltingDog

回答

4

原因是JavaScript變量聲明被掛起。所以即使你的var lastmargintop低於console.log(),它的行爲就好像聲明部分在上面一樣。

所以這...

var lastmargintop = 0; 

$(document).scroll(function() { 
    // ...removed code... 

    console.log(lastmargintop); // expecting 0? you'll get undefined 
    var lastmargintop = margintop; 

}); 

中實際上是解釋爲這樣:

var lastmargintop = 0; 

$(document).scroll(function() { 
    var lastmargintop; 

    // ...removed code... 

    console.log(lastmargintop); // Probably clearer now why you get undefined 
    lastmargintop = margintop; 

}); 

通知的var lastmargintop被移到函數的頂部。這種情況隱含在顯式變量聲明中。

0

首先,如果要將新值lastmargintop打印到控制檯,則需要比之後重新定義它。另外,我不會像這樣兩次定義margintop,然後在定義中調用它。我會在那裏使用一個新的變量名稱。