Javascript 元素 offsetHeight returns returns for 循环中为 0

Javascript element offsetHeight returns returns 0 in for loop

我正在尝试动态获取三列网格中子元素的高度。

i等于2或i大于1时(即当循环内至少有2个元素时),offsetHeight returns渲染高度正确(我在专用 $('#testheight') 元素中显示渲染高度值以供检查。)

但是当i等于1,offsetHeightreturns0时,即使渲染的元素有高度(有一个<img>元素渲染在通过 PHP).

的子元素

我找不到错误!请帮忙!

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个元素时,blocks.length只会是1。因此,当你的for循环开始时,条件i<blocks.length已经为假,因为i也等于1。在for循环中声明var i = 0。希望这对您有所帮助!

改进了代码,检查一下: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,根本不关心第一行。