在固定高度父div中为子div添加省略号

时间:2017-08-21 15:30:21

标签: html css ellipsis

我有一个固定高度的父div,隐藏溢出和其中的多个子div,如何在可见子div之后显示省略号以表示有更多div。

到目前为止,这是我的代码:



.parent {
  display: inline-block;
    padding-left: 10px;
    padding-top: 7px;
    overflow: hidden;
    height: 50px;
}

.child {
  margin-right: 5px;
    color: #fff;
    border-radius: 3px;
    padding: 3px 8px;
    font-size: 12px;
    margin-bottom: 10px;
    background: red;
}

<div class="parent">
  <div class="child">
    first
  </div>
   <div class="child">
    second
  </div>
   <div class="child">
    third
  </div>
   <div class="child">
    fourth
  </div>
</div>
&#13;
&#13;
&#13;

这里隐藏了第三个和第四个孩子,我想在第二个div之后显示点数

此外,子div的数量可能会有所不同,所以我只想在父div溢出时显示点

1 个答案:

答案 0 :(得分:0)

$('.showLessBtn').hide();
var fixedHeight = 50;

var allParents = $('body').find('.parent');
for(var x = 0; x < allParents.length; x++){
  var allChildsOfThisParent = $(allParents[x]).find('.child');
  var parentHeight = 0;
  var childHeight = 0;
  parentHeight = $(allParents[x]).height();
  for(var y = 0; y < allChildsOfThisParent.length; y++){
    childHeight = childHeight +           $(allChildsOfThisParent[y]).height();
  }
  if(childHeight > parentHeight){
    $(allParents[x]).find('.showMoreBtn').show();
  }else{
    $(allParents[x]).find('.showMoreBtn').hide();
  }
}

$(".showMoreBtn").on('click', function(){
  $(this).parent().parent().css({'height':'auto'});
  var parentNewHeight = 0;
  parentNewHeight = $(this).parent().parent().height();
  $(this).parent().find('.showLessBtn').css({'top':parentNewHeight+10});
  
  $(this).hide();
  $(this).parent().find('.showLessBtn').show();
});

$(".showLessBtn").on('click', function(){
  $(this).parent().parent().css({'height':fixedHeight});
  $(this).parent().find('.showMoreBtn').show();
  $(this).hide();
});
.parent {
  display: inline-block;
    padding-left: 10px;
    padding-top: 7px;
    overflow: hidden;
    height: 50px;
    width: 100px;
}

.showMoreBtn, .showLessBtn{
  border: none;
  cursor: pointer;
  position: absolute;
  top: 60px;
  left: 55px;
  height: 10px;
  padding-top:0;
  background: transparent;
}


.child {
    padding: 2px;
}
.child>div{
    color: #fff;
    border-radius: 3px;
    padding: 3px 8px;
    font-size: 12px;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div>
    <button class="showMoreBtn" type="button">.....</button>
    <button class="showLessBtn" type="button">...</button>
  </div>
  <div class="child">
    <div>
      first
    </div>
  </div>
   <div class="child">
    <div>
      second
    </div>
  </div>
   <div class="child">
    <div>
      third
    </div>
  </div>
   <div class="child">
    <div>
      fourth
    </div>
  </div>
</div>