2013-03-19 19 views
0

當我想通了...... See below。我查詢的div層是通過CSS隱藏的,然後在我的位置查詢後顯示在JS中。因爲我從來沒有看到它隱藏,我沒有意識到這是,這就是爲什麼jQuery返回0,0。爲什麼div的jQuery位置()0,0在onload之後,但瞬間之後纔是真正的價值?

我覺得自己像個白癡。

下面的代碼只是意在說明,幷包括了所有我認爲代碼爲必要的,但它留下了一個關鍵的CSS定義和關鍵JS調用:

我有一些一個div層子菜單層的菜單項。

<div id="menuItems"> 
    <div id="menuItem0">Menu Item 0</div> 
    <div id="menuItem1">Menu Item 1</div> 
</div> 

位置和尺寸是在外部CSS中定義的。

#menuItem0 { top: 0px; left: 100px; height: 40px; width: 200px; background-color: green;} 
#menuItem1 { top: 0px; left: 350px; height: 40px; width: 200px; background-color: red;} 

而且在加載腳本應該顯示的菜單項的位置和尺寸:谷歌瀏覽器

$(window).load(function() { 
    prepareMenuItems();  
}); 

function prepareMenuItems() { 
    var numberOfMenuItems = $("#menuItems").children().length; 

    for (var i=0; i<numberOfMenuItems; i++) { 
     console.log("left: "+$("#menuItem" + i).position().left + 
      " top:" + $("#menuItem" + i).position().top + 
      " w:" + $("#menuItem" + i).width() + 
      " h:"+ $("#menuItem" + i).height()); 
    } 
} 

在我的現場演示,我所看到的(最新的)是: 左: 0 top:0 w:200 h:40 left:0 top:0 w:200 h:40

左邊和上邊都是零時,他們不應該是。

如果我強行突破,一旦頁面加載,有一個瞬間的Chrome調試器將評估在$(「#menuItem0」)的手錶。位置()。離開正常。但爲什麼不加載呢?它吐出正確的寬度和高度,所以CSS已經清楚地加載了。而且它知道後面的答案,因爲強制中斷給出了正確的答案,所以這不是我看錯的東西的位置。

幫助!這讓我很生氣。

(對不起,前面的拼寫錯誤我試圖說明性的而不是字面的,我沒有意識到人們會測試給定的代碼。Magritte did so via Fiddler和代碼按預期工作,所以它必須與外部參考有關到CSS或JS什麼的......)。

+0

無法重現。你有錯別字。我修復了它們並將你的例子變成了小提琴:http://jsfiddle.net/wBqT6/ – Travis 2013-03-19 19:15:51

回答

1

我想通了......我是個白癡......我不知道的CSS規則之一是使隱匿在開始和代碼毫秒父DIV以後會使其可見。所以在jQuery查詢它的位置時,圖層被隱藏起來,jQuery的行爲是(我沒有意識到)在div被隱藏時返回0。毫秒後,圖層顯示,現在在休息jQuery按預期工作。當然,祕訣就是不要在開始時隱藏父層div層。

謝謝你們,誰迴應。你們看起來很棒,修復我愚蠢的拼寫錯誤,迫使我進一步研究它,以製作一個工作演示,以更好地證明我的觀點(這導致我找到了解決方案)。

0

似乎爲我工作,你有幾個錯字:http://jsfiddle.net/MQfqA/1/

function prepareMenuItems() { 
    var numberOfMenuItems = $("#menuItems").children().length; 

    for (var i=0; i<numberOfMenuItems; i++) { 
     console.log("left: "+$("#menuItem" + i).position().left + 
      " top:" + $("#menuItem" + i).position().top + 
      " w:" + $("#menuItem" + i).width() + 
      " h:"+ $("#menuItem" + i).height()); 
    } 
} 
0

你的語法是錯誤的。這現在可以運作

$(document).ready(function() { 
    prepareMenuItems();  
}); 

function prepareMenuItems() { 
    var numberOfMenuItems = $("#menuItems").children().length; 

    for (var i=0; i<numberOfMenuItems; i++) { 
     console.log("left: "+$("#menuItem" + i).position().left + 
      " top:"+$("#menuItem" + i).position().top+ 
      " w:"+$("#menuItem" + i).width() + 
      " h:"+ $("#menuItem" + i).height()); 
    } 
} 
0

我的印象還是你忘了關閉第11行的報價?

相關問題