Javascript 仅当空间足够时才显示div

Javascript 仅当空间足够时才显示div,javascript,Javascript,我正在寻找一种解决方案,仅在有空间的情况下显示div 在我博客的帖子页面上,我在左侧边栏中显示最新的帖子,就像这样 我想根据帖子的长度显示不同数量的边栏项。目前,我有三个div显示不同数量的项目,并运行此脚本 if ($("#contentheight").height()>960 && $("#contentheight").height()<1200) { document.getElementById("threeposts").className

我正在寻找一种解决方案,仅在有空间的情况下显示div

在我博客的帖子页面上,我在左侧边栏中显示最新的帖子,就像这样

我想根据帖子的长度显示不同数量的边栏项。目前,我有三个div显示不同数量的项目,并运行此脚本

    if ($("#contentheight").height()>960 && $("#contentheight").height()<1200) {
  document.getElementById("threeposts").className += "hide";
}
else if ($("#contentheight").height()>1200 && $("#contentheight").height()<1880) {
  document.getElementById("fiveposts").className += "hide";
}
else if ($("#contentheight").height()>1880) {
  document.getElementById("sevenposts").className += "hide";
}
if($(“#contentheight”).height()>960&$(“#contentheight”).height()1200&$(“#contentheight”).height()1880){
document.getElementById(“sevenposts”).className+=“隐藏”;
}
然而,这并不方便,对于非常短的帖子,它根本不显示任何项目

是否有一种变通方法,例如,我可以为7项编写代码,但只显示父div可以使用的数量?我试着使用overflow:hidden,但最后你的最终目标被切成了两半


例如,如果有足够的空间容纳三个完整的项目,则会显示这些项目,但之后的任何项目都不会显示。

您可以创建一个隐藏的div或一个未按所需宽度插入DOM的div

然后逐项插入,直到此分区的高度超过您的文章长度。

现在您知道有多少项可以放入该分区。

请尝试以下方法:

$('#container').children().each( function() {
  var top = $(this).top;
  var height = $(this).height;
  if (top + height > $(this).parent().height()) {
    $(this).className += "hide";
  }
});