0

我有一些代码取决于正在加载的 css。
在页脚上加载 javascripts 之前,我在页眉上加载 css

我尝试了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但都失败了。

4

5 回答 5

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);
    }
});
于 2012-07-31T19:27:21.473 回答
0

就绪事件就足够了。

当使用依赖 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);
    }
});
于 2012-07-31T19:32:19.203 回答
0

将 CSS 加载到页眉中,将 JS 加载到页脚中,并包装在 doc-ready 中,就在执行 JS 代码之前应用 CSS 而言,您应该没问题。我猜你的元素没有宽度的原因是它是display: none;,或者只包含浮动元素,或者类似的东西。换句话说 - 我认为这是一个 CSS 问题,而不是 JS 时间问题。尝试进入您的 Firebug/Chrome 控制台,选择有问题的元素并获取其宽度。

于 2012-07-31T19:29:35.840 回答
0

JavaScript 注释不是#,它们是//

错误的

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,因为它是为块范围缩进的,并且到处都缺少大括号/闭包。

于 2012-07-31T19:25:07.963 回答
0
$(window).bind("load", function() {
   // code here
});
于 2019-01-30T07:23:36.053 回答