css知識點——文本溢出的處理方法

1.單行文本超出一定長度之後隱藏

 p{ 
      overflow:hidden;
      white-space: nowrap;
      width: 150px;
}

2.單行文本超出一定長度之後省略號顯示

p{
width:150px;      
white-space: nowrap;
overflow:hidden;
text-overflow:ellipsis;
}


3.多行文本溢出顯示省略號

適用範圍Webkit瀏覽器或者移動端(是WebKit內核的瀏覽器)頁面,可以直接使用Wekit的css擴展屬性

-wekit-line-clamp這是一個 不規範的屬性,它沒有出現在 CSS 規範草案中.

-wekit-line-clamp用來限制在一個塊元素顯示的文本的行數。 爲了實現該效果,它需要組合其他的WebKit屬性。

常見結合屬性:

display: -webkit-box; 必須結合的屬性 ,將對象作爲彈性伸縮盒子模型顯示 。
-webkit-box-orient 必須結合的屬性 ,設置或檢索伸縮盒對象的子元素的排列方式 。

text-overflow: ellipsis;,可以用來多行文本的情況下,用省略號“…”隱藏超出範圍的文本 。

p{
overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
跨瀏覽器兼容的方案

比較簡單的做法是設置相對定位的容器高度,用包含省略號(…)的元素模擬實現;

p {
    position:relative;
    line-height:1.4em;
    /* 3 times the line-height to show 3 lines */
    height:4.2em;
    overflow:hidden;
}
p::after {
    content:"...";
    font-weight:bold;
    position:absolute;
    bottom:0;
    right:0;
    padding:0 20px 1px 45px;
    background:url(http://newimg88.b0.upaiyun.com/newimg88/2014/09/ellipsis_bg.png) repeat-y;
}
注意幾點:

height高度真好是line-height的3倍;

結束的省略號用了半透明的png做了減淡的效果,或者設置背景顏色;

IE6-7不顯示content內容,所以要兼容IE6-7可以是在內容中加入一個標籤,比如用<span class="line-clamp">...</span>去模擬;

要支持IE8,需要將::after替換成:after;

或者不用圖片;

p{position: relative; line-height: 20px; max-height: 40px;overflow: hidden;}
p::after{content: "..."; position: absolute; bottom: 0; right: 0; padding-left: 40px;
background: -webkit-linear-gradient(left, transparent, #fff 55%);
background: -o-linear-gradient(right, transparent, #fff 55%);
background: -moz-linear-gradient(right, transparent, #fff 55%);
background: linear-gradient(to right, transparent, #fff 55%);
}
效果如圖:1.jpg

JavaScript 方案

用js也可以根據上面的思路去模擬,實現也很簡單,推薦幾個做類似工作的成熟小工具:


1.Clamp.js
下載及文檔地址:https://github.com/josephschmitt/Clamp.js
使用也非常簡單:

var myModule = document.getElementById("clamp-this");
$clamp(myModule, {clamp: 3});





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章