[英]Javascript element offsetHeight returns returns 0 in for loop
我试图动态获取三列网格内子元素的高度。
当i
是等于2或当i
大于1(即,当有在循环内最小2个元件), offsetHeight
正确返回呈现高度(I显示在专用的呈现高度值$('#testheight')
检查元素。)
但是,当i
等于1时,即使呈现的元素具有高度(通过PHP在子元素内部呈现的<img>
元素), offsetHeight
返回0。
我找不到错误! 请帮忙!
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
已经为false,因为i
也等于1。声明var i = 0
在for循环中。 希望这可以帮助!
改进了代码,请查看: 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,而不关心第一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.