【问题标题】:jQuery width() incorrect immediately after document ready?文档准备好后,jQuery width() 立即不正确?
【发布时间】:2025-12-16 04:05:01
【问题描述】:

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

更新 请参阅下面的评论。原来有一个资产,一种嵌入字体,加载需要一瞬间。

【问题讨论】:

    标签: jquery html wordpress jquery-selectors


    【解决方案1】:

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

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

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

    "window load 事件在整个页面完成后稍后执行 完全加载,包括所有帧、对象和图像。所以 应放置涉及图像或其他页面内容的功能 在窗口或内容标签本身的加载事件中。" *

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

    *引用来自4loc

    【讨论】:

    • 我想通了...我在菜单中使用了嵌入字体。 dom 元素的宽度由浏览器的默认字体决定,直到字体完全加载。不知何故,你的回答让我想起了嵌入的字体!