解决一行文本溢出隐藏点击展开之后全部显示并自动换行每行长度一致问题

一行数据文本内容太多,把页面撑得很长影响美观。该方法可以实现当一行文本内容超过固定长度后,收缩起来,显示一个“展开”按钮,用户一点击后就显示全部内容。当然多行文本也同样适用,(若是全部是中文也可以使用判断判断字符串长度的方法,中文占用两个字符,但是若文章中含有英文就不适合了,因为字母i所占用的长度非常短一个汉字所占用的字符多余2个i,就会出现长短不一的情况;)本文所展示方法解决了这个问题。

HTML

<div style="width: 250px; position: absolute;">
    <div id="content">
        first my gaze toward the moon, but the moon shines on the ditch. “我本一心向明月,奈何明月照沟渠”
    </div>
    <a Onclick='more()' id='expand'>
        展开
    </a>
    <a Onclick='pack()' id="pack">
        收起
    </a>
</div>

css

#content{
   width: 150px;
   height: 25px; 
   float:left;
   overflow: auto;
   word-wrap:break-word;
   word-break: break-all;
   text-overflow:ellipsis;
   white-space:nowrap;     
}
a{
   float:right;
   margin-left: 30px;
   position: absolute;
   top: 0;
   right: 0;
}
#pack{
   display: none;
}

JS

window.onload=function(){
    // element.scrollHeight---文章内容的实际高度   element.clientHeight---文章内容的显示高度
    // element.scrollWidth---文章内容的实际宽度   element.clientWidth ---文章内容的显示宽度
    var element=document.getElementById("content")
    if(element.scrollHeight>element.clientHeight){
        element.style='overflow:hidden;'
    }else{
        document.getElementById("expand").style="display:none"
    }
    
}
function more(){
    document.getElementById("content").style='overflow:visible; white-space:normal;'
    document.getElementById("expand").style="display:none"
    document.getElementById("pack").style="display:block"
 }
 function pack(){
    document.getElementById("content").style='display:block;overflow:hidden'
    document.getElementById("expand").style="display:block"
    document.getElementById("pack").style="display:none"
}

猜你喜欢

转载自www.cnblogs.com/jlfw/p/12209009.html
今日推荐