jQuery: add elements until a particular height is reached

霸气de小男生 提交于 2019-12-24 00:58:46

问题


I have a column on the left with a few articles. This height is dynamic and changes based on the published content. I have a column on the right that is typically shorter. I'm pulling 3 large elements and then another 5 small ones and I want to fill in the right column with extra elements until it's close to the height of the column on the left.

So I pull all the large elements (3) and assume that this is shorter than the left. Then I pull the other 5 with a class attached to hide them (for those w/o JS). Now I want to iterate through the 5 elements and keep adding until I can't add anymore without making that column longer than the one on the left. Here's what I have so far:

var hLeft = $('#home-col-left').outerHeight();
var hRight = $('#home-col-right').outerHeight();
var hRunning = hChecking = 0;

$('#home-col-right').children().each( function () {
    hChecking = hRunning + 60;
    if (hChecking < hLeft) $(this).removeClass('hidden');   
    hRunning = hRunning + $(this).outerHeight();
})

The problem is that I can't check the height of the element while it's hidden so I use the hChecking var to assume that the new ones are about 60 pixels tall. This isn't ideal because they can be less or more than that.

Any way to get this working while still allowing the elements to be hidden for folks without JS? Thanks!


回答1:


This works:

var containerDiv = $('#someElement');
while( containerDiv.height() < 500 ){
    $('<p>Test</p>').appendTo(containerDiv);
}


来源:https://stackoverflow.com/questions/8771897/jquery-add-elements-until-a-particular-height-is-reached

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!