移動端的text-overflow多行文字溢位顯示省略號(…)
大家應該都知道用text-overflow:ellipsis
屬性來實現單行文字的溢位顯示省略號(…)。當然部分瀏覽器還需要加寬度width
屬性。
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
但是這個屬性並不支援多行文字溢位顯示省略號,這裡根據應用場景介紹幾個方法來實現這樣的效果。
WebKit瀏覽器或移動端的頁面
在WebKit瀏覽器或移動端(絕大部分是WebKit核心的瀏覽器)的頁面實現比較簡單,可以直接使用WebKit的CSS擴充套件屬性(WebKit是私有屬性)-webkit-line-clamp
;注意:這是一個 不規範的屬性(unsupported WebKit property
),它沒有出現在 CSS 規範草案中。
-webkit-line-clamp
用來限制在一個塊元素顯示的文字的行數。 為了實現該效果,它需要組合其他的WebKit屬性。
常見結合屬性:
display: -webkit-box; -webkit-box-orient text-overflow: ellipsis;
overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
這個屬性比較合適WebKit瀏覽器或移動端(絕大部分是WebKit核心的)瀏覽器。
具體例子可以檢視http://www.css88.com/webkit/-webkit-line-clamp/
跨瀏覽器相容的方案
比較靠譜簡單的做法就是設定相對定位的容器高度,用包含省略號(…)的元素模擬實現;
例如:
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://www.css88.com/wp-content/uploads/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
;
JavaScript 方案
用js也可以根據上面的思路去模擬,實現也很簡單,推薦幾個做類似工作的成熟小工具:
1.Clamp.js
下載及文件地址:https://github.com/josephschmitt/Clamp.js
使用也非常簡單:
var module = document.getElementById("clamp-this-module"); $clamp(module, {clamp: 3});
2.jQuery外掛-jQuery.dotdotdot
這個使用起來也很方便:
$(document).ready(function() { $("#wrapper").dotdotdot({ //configuration goes here }); });