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

oro*_*edd 7 html wordpress jquery 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);
});
Run Code Online (Sandbox Code Playgroud)

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

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

dsg*_*fin 15

这可能与$(window).load第一个例子中的缺乏有关.

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

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

" 当完整页面完全加载时,窗口加载事件会稍后执行,包括所有帧,对象和图像.因此,涉及图像或其他页面内容的函数应放在窗口或内容标记本身的加载事件中. "*

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

*来自4loc的报价.

  • 我想通了......我在菜单中使用嵌入字体.dom元素的宽度由浏览器的默认字体确定,直到字体完全加载.不知怎的,你的回复让我想起了嵌入式字体! (7认同)