2016-08-08 75 views
0

我想動態獲取三列網格內的子元素的高度。Javascript元素offsetHeight返回for循環返回0

i等於2,或者當i大於1時(即,當有在循環內最小2個元件),offsetHeight正確返回呈現高度(I在用於專用$('#testheight')元件顯示的呈現高度值)

但是,當i等於1時,offsetHeight將返回0,即使呈現的元素具有高度(在子元素中通過PHP呈現<img>元素)。

我找不到錯誤!請幫忙!

function makeGrid(){ 
    var blocks = document.getElementById("grid_container").children; 
    var pad = 0, cols = 3, newleft, newtop; 
    var max_height = 0; 
    var newoffsetheight = 0; 
    for(var i = 1; i < blocks.length; i++){ 
    if (i % cols == 0) { 
     newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad; 
     max_height = Math.max(max_height, newtop + blocks[i-cols].offsetHeight); 
     blocks[i].style.top = newtop+"px"; 
     newoffsetheight = blocks[i].offsetHeight; 
    } 
    else { 
     if(blocks[i-cols]){ 
     newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad; 
     blocks[i].style.top = newtop+"px"; 
     } 
     newleft = (blocks[i-1].offsetLeft + blocks[i-1].offsetWidth) + pad; 
     blocks[i].style.left = newleft+"px"; 
     newoffsetheight = blocks[i].offsetHeight; 
    } 
    } 
    $('#testheight').html(newoffsetheight); 
} 
+1

爲什麼你開始你的循環'i'設置爲1,而不是0? –

+0

@LambdaNinja根據註釋,如果'int i = 0;'是你的循環初始化器,你會希望'i <= blocks.length;'循環遍歷數組循環中的每一項。 –

+0

謝謝,但即使我將循環更改爲:for(var i = 0; i <= blocks.length; i ++){},它不顯示正確的值... – rainerbrunotte

回答

1

提高了代碼,查出來:https://jsfiddle.net/0otvhgkg/8/

function renderGrid(){ 
var blocks = document.getElementById("grid_container").children; 
var pad = 0, cols = 3, newleft 
var newtop = 0 
var max_height = blocks.length ? blocks[0].offsetHeight : 0; 

    for(var i = 1; i < blocks.length; i++){ 
     if (i % cols == 0) { 
      newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;  
      blocks[i].style.top = newtop+"px"; 
      max_height = Math.max(max_height, newtop + blocks[i].offsetHeight); 
     } else { 
      if(blocks[i-cols]){ 
       newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad; 
       blocks[i].style.top = newtop+"px"; 
       max_height = Math.max(max_height, newtop + blocks[i-cols].offsetHeight); 
      } 
      newleft = (blocks[i-1].offsetLeft + blocks[i-1].offsetWidth) + pad; 
      blocks[i].style.left = newleft+"px"; 
      max_height = Math.max(max_height, newtop + blocks[i-1].offsetHeight); 
     } 
    } 
    $('#grid_container').css('height', max_height); 
} 
window.addEventListener("load", renderGrid, false); 
window.addEventListener("resize", renderGrid, false); 

問題是我們計算MAX_HEIGHT只有當新的行創建並沒有在意第一行任何責任。

+0

非常感謝!但它只適用於最低有2個區塊的情況,如果只有一個區塊,它仍會破損:http://jsfiddle.net/0otvhgkg/4 – rainerbrunotte

+0

已更新:http://jsfiddle.net/0otvhgkg/5/ –

+0

hmm,幾乎在那裏,但東西仍然打破... http://jsfiddle.net/0otvhgkg/7/ – rainerbrunotte

2

當只有1環內元素,blocks.length只會是1。因此,當你的for循環開始,病情i<blocks.length已經是假的,因爲i也等於1.申報var i = 0 for循環。希望這可以幫助!