單行截斷:
span { display: inline-block; // 如果不是block元素,還需要設置這個。 width: 150px; // 超出的寬度 overflow: hidden; // 超出隱藏 text-overflow: ellipsis; //超出用省略號 white-space: nowrap; // 不換行 }
多行截斷:
多行截斷有好幾種方法,
1: 最簡單,使用-webkit-line-clamp , 當然了,只能用在webkit內核瀏覽器, 並且不支持自定義點擊展開的樣式。
p { width: 400px; // 超過這個寬度 text-overflow: ellipsis; // 使用省略號 display: -webkit-box; // 必須使用這個 overflow: hidden;// 必須使用,超出隱藏 -webkit-line-clamp: 4; // 必需設置, -webkit-box-orient: vertical; // 設置裏面元素排列順序 text-align: justify; // 裏面問題排列方式 }
2: 也是面試中回答的方式,使用僞類。。。這個由於要使用js判斷是否超出,因此適用於,你已經知道是大段文字的情景。 但是面試官不是很滿意這個方式,嗚嗚嗚(ಥ _ ಥ)
p{ position: relative; height: 36px; // 面試官說這個是定死的,所以不靈活。。。感覺很奇怪啊,不是死的話,怎麼知道什麼情況溢出? overflow: hidden; line-height: 18px; } p::after{ // 這個是一直有省略號,所以需要js判斷是否超出,如果超出的話,就加一個class。 content: '...'; position: absolute; bottom:0; right: 0; }
3:使用float, 挺複雜的,不喜歡float......, 使用float時候,省略號是一個dom節點,因此可以添加事情和樣式, 自定義程度高!
<div class="container"> <div class="content">騰訊成立於1998年11月,是目前中國領先的互聯網增值服務提供商之一。成立10多年來,騰訊一直秉承“一切以用戶價值爲依歸”的經營理念,爲億級海量用戶提供穩定優質的各類服務,始終處於穩健發展狀態。2004年6月16日,騰訊控股有限公司在香港聯交所主板公開上市(股票代號700)。</div> <div class="standard"></div> <div class="more">...更多</div> </div>
其中standard是一個標準,超過它的高度時候,就會顯示省略號,container是個容器,超過他的最大高度,就hidden。 三個div都float:right,其中content的margin-left:-standard的寬度,把standard給讓出來,讓standard出現在左側。
.container{ max-height: 54px; // 最大高度 overflow: hidden; // 超出隱藏 line-height: 18px; // 方便計算幾行。。 font-size:12px; } .container div{ // 三個元素都設置float float: right; } .content{ margin-left: -50px; // 這是第一個元素,由於他寬度是100%,所以需要給standard位置。 width:100%; position:relative; background: hsla(229, 100%, 75%, 0.5) } .standard{ width: 50px; //寬度隨意, 需要與上面margin-left一樣 height: 54px; // 超出這個高度會出現more元素 position:relative; color:transparent; background: hsla(334, 100%, 75%, 0.5); } .more{ width:50px; // 這個元素可自定義,寬度 height:18px; position: relative; left: 100%; // 確定位置, transform: translate(-100%,-100%);// 確定位置 background: linear-gradient(90deg, rgba(255, 255, 255, 0), #fff 20%, #fff); // 這是使用漸變,因爲more元素會覆蓋住content元素。 }
總結: 可以直接使用float方法,方便自定義樣式及監聽事件,並且兼容性好,是暫時最完美的解決方案。就是略複雜,不過網上有可以直接拿來用哦~
最後一個挺複雜的,看了半天,感覺網上很多,可以直接拿來用, 不需要特別理解透徹,畢竟過不了幾年,應該就會有內置屬性了。。。