2013-03-27 43 views
7

由於某種原因$("...").width()在文檔準備好後立即返回錯誤的值。jQuery 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的菜單項的寬度和調整他們,使他們始終適合我的響應式設計。沒有應該引起這種變化的圖像或資產。

更新 查看我的評論如下。事實證明,有一種資產,一種嵌入式字體,需要一秒鐘才能加載。

回答

15

這可能與第一個例子中缺少$(window).load有關。

「的文件準備事件已經執行時的HTML文檔是 加載和DOM是準備好了,即使所有的顯卡都沒有加載 呢。如果你想掛鉤的事件窗口加載前 之前的某些元素,那麼$(document).ready就是正確的地方。「 *

$(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來源。

+6

我想通了......我在菜單中使用了嵌入式字體。 dom元素的寬度由瀏覽器的默認字體決定,直到字體完全加載。不知何故,你的迴應讓我想起了嵌入式字體! – orourkedd 2013-03-27 20:34:25