jQuery width() incorrect immediately after documen

2019-01-26 10:20发布

问题:

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.

回答1:

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.