无法在页面刷新时获取元素宽度

时间:2014-12-23 22:27:03

标签: javascript css width element

我有以下代码:

  //get the largest block: if no block, apply to first block
  var previous = $('.block-grid .block-group .block.block-lg');

  var blocks = $('.block-grid .block-group .block');

  blocks.last().css({'left': (previous.width() + previous.position().left), 'top':    previous.position().top});

当我刷新页面时,这部分:previous.width(),返回0.通常它应该返回400,这是最大块的大小。但是,当我导航到页面的URL时,它返回400.为什么页面刷新会使宽度值为0?我非常困惑,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我实际上已经设法让这个工作。这是一个非常简单的解决方案。我只是将我的解决方案包装在$(window).load()中,所以它看起来像这样:

$(window).load(function(){

  //get the largest block: if no block, apply to first block
  var previous = $('.block-grid .block-group .block.block-lg');

  var blocks = $('.block-grid .block-group .block');

  blocks.last().css({'left': (previous.width() + previous.position().left), 'top':    previous.position().top});

});