文档准备好后,jQuery width()是否立即生效?

时间:2013-03-27 20:19:25

标签: jquery html wordpress jquery-selectors

由于某种原因,$("...").width()在文档就绪后立即返回错误的值。

我看到了这些价值观:

文件准备就绪后立即:

$(document).ready(function(){
  $("li.active a").width() //returns 76 - incorrect
});

$(document).ready(function(){
  $(window).load(function(){
    $("li.active a").width() //returns 59 - the correct value
  });
});

$(document).ready(function(){
  setTimeout(function(){
    $("li.active a").width() //returns 59 - the correct value
  }, 100);
});

我正在获取wordpress菜单项的宽度并调整它们的大小,以便它们始终适合我的响应式设计。没有图像或资产可能导致此更改。

更新 请参阅下面的评论。事实证明,有一种资产,一种嵌入式字体,只需要一瞬间加载。

1 个答案:

答案 0 :(得分:15)

可能与第一个例子中缺少$(window).load有关。

  

文档就绪事件在HTML-Document出现时已经执行   加载并且DOM已准备就绪,即使所有图形都未加载   然而。如果您想在之前连接某些元素的事件   窗口加载,然后$(文件).ready是正确的地方。“*

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});

  

“完整页面后,窗口加载事件会稍后执行   满载,包括所有帧,对象和图像。因此   应放置与图像或其他页面内容有关的功能   在窗口或内容标记本身的加载事件中。“*

$(window).load(function() {
 // executes when complete page is fully loaded (all frames, objects and images)
 alert("window is loaded");
});

* 来自4loc的报价。

相关问题