1,首先來一個固定寬度,在一行顯示,超出隱藏,顯示省略號的樣式
display:block;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
2,其實來一個可以設置讓它顯示多少行后再顯示省略號,這只能用私有屬性解決了
text-overflow: -o-ellipsis-lastline; overflow: hidden; text-overflow: ellipsis; display: -webkit-box;/*重點,不能用block等其他*/ -webkit-line-clamp: 2;/*重點IE和火狐不支持*/ -webkit-box-orient: vertical;/*重點*/
因為 -webkit-line-clamp: 2 是webkit的私有屬性,其他瀏覽器不可以用。所以在網上找了一下,有個插件還是很好用的,完美的實現了這個屬性。
還可以配置很多屬性,比如 是否動畫展開,不一定要顯示省略號,可以顯示其他符號,是否啟用 -webkit-line-clamp: 這個屬性等等;
下載地址 https://github.com/josephschmitt/Clamp.js
首先引入
<script src="../clamp.js"></script>
//調用方法:$clamp(dom,options); dom是節點,options是配置項
用這個插件需要注意一下事項:
我在用這個插件的時候,IE和火狐下面形態各異,火狐在第二行還沒到第二行的末尾處(甚至還有很寬的距離)就顯示省略號了。IE有時候也出現。
查看了一下源碼發現 這個和指定不指定line-height有關系,因為源碼中會獲取line-height獲取高度 來判斷顯示省略號的;
function getLineHeight(elem) {//計算高度 var lh = computeStyle(elem, 'line-height'); if (lh == 'normal') {//如果DOM 節點沒有指定line-height 那么IE會輸出默認的normal 火狐會輸出22px lh = parseInt(computeStyle(elem, 'font-size')) * 1.2; } return parseInt(lh); }
如果沒有指定行高,IE下面computeStyle(elem, 'line-height');就會返回 nomal。火狐下面就會根據瀏覽器返回[22px]
再接着看源碼
if (supportsNativeClamp && opt.useNativeClamp) {//如果支持webkit-line-clamp 直接用 sty.overflow = 'hidden'; sty.textOverflow = 'ellipsis'; sty.webkitBoxOrient = 'vertical'; sty.display = '-webkit-box'; //sty.wordWrap = 'break-word'; sty.webkitLineClamp = clampValue; if (isCSSValue) { sty.height = opt.clamp + 'px'; } } else { var height = getMaxHeight(clampValue); if (height <= element.clientHeight) { clampedText = truncate(getLastChild(element), height); } }
如果用戶在樣式中指定了line-height,IE和火狐下面 就會 height == element.clientHeight(一直等於),則就一直會走
clampedText = truncate(getLastChild(element), height); 這段代碼。所以需要把 height <= element.clientHeight 的= 號去掉。(具體沒去研究,看源碼truncate函數即可,下次補上)
沒有指定的話 IE就會根據 font-size*12 = 16*1.2 = 19.2
火狐則是一直是22px ,這就有很大差異了。導致
<script> var header = document.getElementsByTagName('h1')[0], $clamp(header, {clamp: 2}); //還可以配置如下 選項 。options包括:clamp——行數,useNativeClamp——是否使用-webkit-line-clamp屬性,trucationChar——省略的符號(不限於省略號),truncationHTML——省略的內容(不限於符號),animate——是否實現動畫折疊。 </script>
還有一個插件 也不叫好用,不過這個插件好像只能設置固定的寬高,超出寬高才會隱藏,不過也多了一些配置(比如,+號折疊,展開。控制多少個字符顯示燈)
jQuery.dotdotdot