0

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

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

但是,当i等于 1 时,offsetHeight返回 0,即使呈现的元素具有高度(<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);
}
4

2 回答 2

2

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

于 2016-08-08T17:11:26.587 回答
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 。

于 2016-08-10T09:21:43.937 回答