2012-07-31 68 views
0

我有一些代碼取決於被加載的CSS。
我加載CSS的頭之前我加載的JavaScript的頁腳CSS完全加載後運行Javascript

我嘗試了JavaScript和$(document).ready



$(document).ready(function() { 
    var bar_position, width; 
    bar_position = $('body').height() - 38; 
    width = $('body').width(); 
    console.log(bar_position); 
    if (width <= 480) { 
    console.log("Entered"); 
    $('#accounts-bar').css("top", bar_position); 
    } 
}); 

我試過$(window).ready$(window).load,但他們都失敗。

+3

你需要$(文件)。就緒,而不是窗口。 – 2012-07-31 19:23:36

+2

爲什麼你不在塊語句中使用'{}'?你的代碼很混亂... – 2012-07-31 19:23:54

+1

'$(document).ready'或者只是'$ - >'順便說一句,這是CoffeeScript嗎? – Sandro 2012-07-31 19:24:36

回答

0

JavaScript comments#,他們是//

錯誤

bar_position = $('body').height() - 38 #38 is the size of the bar 

bar_position = $('body').height() - 38 //38 is the size of the bar 

而且還有一堆其他錯誤,其中的代碼將無法運行。猜測你錯過了一個標籤,這不是純粹的JavaScript,因爲它縮進了作用域範圍,並且遺漏了大括號/關閉。

+0

我認爲這是CoffeScript – 2012-07-31 19:26:08

+0

看來他使用的是咖啡腳本 – jackwanders 2012-07-31 19:26:25

+0

是的,在Coffeescripts中,評論就像那樣。 – Jashwant 2012-07-31 19:27:43

3

你的代碼是真的搞砸了(除非你正在使用的CoffeeScript)。這是它應該是什麼:

$(function() { 
    bar_position = $('body').height() - 38; //38 is the size of the bar 
    width = $('body').width(); 
    console.log(bar_position); 
    if (width <= 480) { //480 is the mobile width 
     console.log("Entered"); 
     $('#accounts-bar').css("top", bar_position); 
    } 
}); 
0

使用CSS的頭被加載,JS在頁腳,幷包裹在一個文檔已經,在JS代碼執行之前,你應該沒問題。我猜你的元素沒有寬度的原因是它是display: none;,或只包含浮動元素,或沿着這些線。換句話說 - 我認爲這是一個CSS問題,而不是JS時間問題。嘗試進入Firebug/Chrome控制檯,選擇相關元素並獲取其寬度。

+0

不,我大概設置了延遲1000,然後它工作。點是正在加載後的CSS。 – daniel 2012-08-01 00:22:34

0

ready event應該就足夠了。

當使用依賴於CSS樣式屬性的值的腳本, 它引用腳本之前引用外部樣式或嵌入樣式 元素是很重要的。

在代碼依賴於加載資源的情況下(例如,如果需要 尺寸的圖片),代碼應該放置在加載事件的 處理程序中。

此外,您的JavaScript無效。如果它應該是的CoffeeScript,你缺少 - >:

$(document).ready -> 
    bar_position = $('body').height() - 38 #38 is the size of the bar 
    width = $('body').width() 
    console.log(bar_position) 
    if (width <= 480) #480 is the mobile width 
    console.log("Entered"); 
    $('#accounts-bar').css("top", bar_position) 
    return 

如果它應該是JavaScript的,你有更多的問題:

$(document).ready(function(){ 
    bar_position = $('body').height() - 38; //38 is the size of the bar 
    width = $('body').width(); 
    console.log(bar_position); 
    if (width <= 480) //480 is the mobile width { 
     console.log("Entered"); 
     $('#accounts-bar').css("top", bar_position); 
    } 
}); 
相關問題