要實現如下圖片的效果,每個欄目的寬度不確定,總長度一定,欄目多了最后顯示...欄目
image.png
html如下:
<div class="box">
<div class="ne">我就問你ne不ne</div>
<div class="ne">你就說我ne不ne</div>
<div class="ne">我不ne</div>
<div class="ne">你ne</div>
<div class="ne">沒有最ne</div>
<div class="ne">只有更ne</div>
<div class="ne">就你ne</div>
<div class="ne">再說我ne我哭了</div>
<div class="ne">你哭你也ne</div>
<div class="ne">哇哇哇哇ne哭了</div>
<div class="ne">艾瑪哭起來更ne了</div>
<div class="overflow">...</div>
</div>
css如下:
<style>
.box{
width:800px;
overflow:hidden;
}
.ne{
float:left;
height:30px;
line-height: 30px;
background:#ddd;
color:#333;
border-radius: 5px;
margin:0 10px 10px 0;
text-align: center;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
padding:0 10px;
}
.overflow{
float:left;
height:30px;
line-height: 30px;
background:#ddd;
color:#333;
border-radius: 5px;
margin:0 10px 10px 0;
text-align: center;
padding:0 10px;
display: none;
}
</style>
js如下:
<script>
var length;
for(var i=1;i<$('.ne').length;i++){
if(length<$('.box').width()){
// 算出每個塊的大小
length += $('.ne').eq(i).width() + 2*parseInt($('.ne').eq(i).css('padding-left')) + parseInt($('.ne').eq(i).css('margin-right'));
}else{
// 超出總長度就取整 后面的隱藏并顯示...
$(".ne").filter(".ne:gt("+(i-3)+")").hide ();
$('.overflow').show();
}
}
</script>
知識點:
gt(n),n后面的所有元素;
lt(n),n前面的所有元素
點擊下載 demo