7

出于某种原因$("...").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 菜单项的宽度并调整它们的大小,以便它们始终适合我的响应式设计。没有应该导致此更改的图像或资产。

更新 见下面我的评论。原来有一个资产,一种嵌入的字体,需要一秒钟才能加载。

4

1 回答 1

17

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

“当加载 HTML 文档并且 DOM 准备就绪时,文档就绪事件已经执行,即使尚未加载所有图形。如果您想在窗口加载之前为某些元素连接事件,那么 $(文件)。准备好是正确的地方。” *

$(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

于 2013-03-27T20:21:11.893 回答