在制作网页或移动端有时会用到一个效果,类似文章标题和文章描述的排列总是保持一样的行数,要么标题总是一行,多出的省略,要么标题内容1:3或2:2或3:1这样,今天练习这样的效果。
实现的原理:给标题和内容分别加上行高,获取标题的高度除以自身的行高,得知标题的行数,再分配内容的行数即可。
<style>
*{padding: 0;margin: 0; font-family: 'Microsoft Yahei'}
.book{
width: 320px;
border: 1px solid #ccc;
}
.bookli{
padding: 5px 10px;
border-bottom: 1px solid #ccc;
}
.bookdiv{
width: 300px;
overflow: hidden;
}
.title{
color:#666;
margin: 10px 0;
line-height: 23px; //标题的行高
}
.desc{
line-height: 23px; //内容的行高
overflow: hidden;
}
</style>
<h2>十大名花排行榜</h2>
<div class="book">
<ul>
<li class="bookli">
<div class="bookdiv">
<h4 class="title">好一朵魅力的茉莉花</h4>
<p class="desc">茉莉花,别名:茉莉,拉丁文名:木犀科、素馨属直立或攀援灌木,高达3米。小枝圆柱形或稍压扁状,有时中空,疏被柔毛。叶对生,单叶,叶片纸质,圆形、椭圆形、卵状椭圆形或倒卵形,两端圆或钝,基部有时微心形,在上面稍凹入或凹起,下面凸起,细脉在两面常明显,微凸起,除下面脉腋间常具簇毛外,其余无毛;裂片长圆形至近圆形,先端圆或钝。果球形,呈紫黑色。</p>
</div>
</li>
<li class="bookli">
<div class="bookdiv">
<h4 class="title">好一朵魅力的茉莉花好一朵魅力的茉莉花好一朵魅力的茉莉花</h4>
<p class="desc">茉莉花,别名:茉莉,拉丁文名:木犀科、素馨属直立或攀援灌木,高达3米。小枝圆柱形或稍压扁状,有时中空,疏被柔毛。叶对生,单叶,叶片纸质,圆形、椭圆形、卵状椭圆形或倒卵形,两端圆或钝,基部有时微心形,在上面稍凹入或凹起,下面凸起,细脉在两面常明显,微凸起,除下面脉腋间常具簇毛外,其余无毛;裂片长圆形至近圆形,先端圆或钝。果球形,呈紫黑色。</p>
</div>
</li>
<li class="bookli">
<div class="bookdiv">
<h4 class="title">好一朵魅力的茉莉花好一朵魅力的茉莉花好一朵魅力的茉莉花好一朵魅力的茉莉花好一朵魅力的茉莉花</h4>
<p class="desc">茉莉花,别名:茉莉,拉丁文名:木犀科、素馨属直立或攀援灌木,高达3米。小枝圆柱形或稍压扁状,有时中空,疏被柔毛。叶对生,单叶,叶片纸质,圆形、椭圆形、卵状椭圆形或倒卵形,两端圆或钝,基部有时微心形,在上面稍凹入或凹起,下面凸起,细脉在两面常明显,微凸起,除下面脉腋间常具簇毛外,其余无毛;裂片长圆形至近圆形,先端圆或钝。果球形,呈紫黑色。</p>
</div>
</li>
<li class="bookli">
<div class="bookdiv">
<h4 class="title">好一朵魅力的茉莉花</h4>
<p class="desc">茉莉花,别名:茉莉,拉丁文名:木犀科、素馨属直立或攀援灌木,高达3米。小枝圆柱形或稍压扁状,有时中空,疏被柔毛。叶对生,单叶,叶片纸质,圆形、椭圆形、卵状椭圆形或倒卵形,两端圆或钝,基部有时微心形,在上面稍凹入或凹起,下面凸起,细脉在两面常明显,微凸起,除下面脉腋间常具簇毛外,其余无毛;裂片长圆形至近圆形,先端圆或钝。果球形,呈紫黑色。</p>
</div>
</li>
</ul>
</div>
window.onload=function(){
//兼容不能使用getElementsByClassName的浏览器
function getClass(clas){
var cls=document.getElementsByTagName('*');
var arr=[];
for(var i=0;i<cls.length;i ){
if(clas==cls[i].className){
arr.push(cls[i]);
}
}
return arr;
}
//控制行数的函数
function controlRow(title,content){
var title=getClass(title);
var desc=getClass(content);
var titleheight;
var descheight;
for(var j=0;j<title.length;j ){
(function(index){
// 获取css样式
if(window.getComputedStyle!="undefined"){ //兼容火狐、谷歌等主流浏览器
titleheight=window.getComputedStyle(title[index],null)['line-height'];
descheight=window.getComputedStyle(desc[index],null)['line-height'];
}else{ //兼容ie浏览器
titleheight=title[index].currentStyle['line-height'];
descheight=desc[index].currentStyle['line-height'];
}
var titleH=titleheight.substr(0,titleheight.length-2);
var descH=descheight.substr(0,descheight.length-2);
// 如果标题高度=行高,那么内容高度则是内容行高的3倍,内容 标题总是保持4行
if(title[index].offsetHeight/titleH==1){
desc[index].style.height=3*descH 'px';
}else if(title[index].offsetHeight/titleH==2){
desc[index].style.height=2*descH 'px';
}else if(title[index].offsetHeight/titleH==3){
desc[index].style.height=1*descH 'px';
}else{
alert("sorry,浏览器不兼容");
}
})(j);
}
}
controlRow('title','desc');
}
测试了谷歌和火狐。ie被我卸了一个文件,打不开。所以没测试。有测试的朋友也可以告诉我一声,谢啦。