2012-07-31 71 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); 
    } 
}); 
相关问题