文档准备好后,jQuery width()不正确吗? [英] jQuery width() incorrect immediately after document ready?

查看:96
本文介绍了文档准备好后,jQuery width()不正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我看到这些值:

立即在文档准备就绪后:

  $(document).ready(function(){
$(li.active a)。width()//返回76 - 不正确
});
$ b $(document).ready(function(){
$(window).load(function(){
$(li.active a)。width )//返回59 - 正确的值
});
});
$ b $(document).ready(function(){
setTimeout(function(){
$(li.active a)。width()//返回59 - 正确的值
},100);
});

我得到wordpress菜单项的宽度并调整它们的大小,以便它们始终适合我的响应设计。没有图像或资产会导致此更改。



更新
请参阅下面的注释。事实证明,这是一种资产,一种嵌入式字体,需要一秒钟才能加载。

这可能与在第一个例子中缺少 $(window).load
$ b


即使所有图形还没有加载
,当文档就绪事件在HTML文档被加载并且DOM已准备就绪时都会执行。如果您想要挂钩在窗口加载
之前为某些元素添加事件,然后$(document).ready就是正确的地方。 *



  $(document).ready(function(){
//在加载HTML文档并准备好DOM时执行
alert(document is ready);
});







The <当整个页面完全加载
时(包括所有框架,对象和图像),稍后会执行一次窗口加载事件,因此涉及图像或其他页面内容的
函数应放置$在窗口或内容标签本身的加载事件中为b $ b。 *



  $(window).load(function(){
//当完整页面完全加载时(所有框架,对象和图像)执行
alert(window is loaded);
});

* 来自 4loc


For some reason $("...").width() is returning the wrong value immediately after document ready.

I'm see these values:

Immediately after document ready:

$(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);
});

I'm getting the width of wordpress menu items and resizing them so that they always fit in my responsive design. There are no images or assets that should cause this change.

Update See my comment below. Turns out there was an asset, an embedded font, that took a split second to load.

解决方案

It could be to do with the lack of $(window).load in the first example.

"The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place." *

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


"The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself." *

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

*Quotes sourced from 4loc.

这篇关于文档准备好后,jQuery width()不正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆