Javascript元素offsetHeight返回for循环中的返回0

时间:2016-08-08 17:03:46

标签: javascript for-loop offsetheight

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

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);
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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。