只有足够的空间才能显示div

时间:2012-10-17 11:17:48

标签: javascript

我正在寻找一个只显示div的解决方案,如果有空间的话。

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

No Nay Never post page

我想根据帖子的长度显示不同数量的侧边栏项目。目前我有三个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";
}

然而,这并不方便,对于非常短的帖子,它根本没有显示任何项目。

是否有一种解决方法,例如,我可以为7个项目编码,但只显示父div可以采用的数量?我尝试使用溢出:隐藏,但最后你最终将最终项目切成两半。

例如,如果有足够的空间容纳三个完整的项目,那么它们将被显示,但之后不会显示。

2 个答案:

答案 0 :(得分:0)

您可以创建一个隐藏的div或div,它不会以所需的宽度插入DOM中。

然后逐项插入,直到此div的高度超过帖子的长度 现在您知道有多少项适合div。

答案 1 :(得分:0)

尝试这样的事情:

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