3 回答

TA貢獻1851條經驗 獲得超3個贊
您可以使用CSS做到這一點。它僅適用于webkit瀏覽器,但對其他瀏覽器具有后備功能。
采用 :
display: -webkit-box;
-webkit-line-clamp: $lines-to-show;
-webkit-box-orient: vertical;
height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
隨著:
max-width: $maxwidth;
overflow: hidden;
text-overflow: ellipsis;

TA貢獻1845條經驗 獲得超8個贊
我之所以發布此信息,是因為我認為我的解決方案沒有流行的解決方案復雜,該解決方案涉及偽元素和浮點行為。我最近不得不創建一個可以在IE7中使用的解決方案,因此偽元素最初不是一個選擇。
該技術涉及4個元素:
確定內容最大高度的塊級容器
文本內容的內聯包裝
內聯包裝中包含的省略號
內聯包裝中的一個“填充”元素,當文本內容未超出容器的尺寸時,將省略號閉塞
與以前的僅使用CSS的解決方案一樣,該技術要求內容使用純色背景或固定位置的背景圖像:省略號需要使文本的某些部分變得晦澀難懂,而填充則需要使省略號的晦澀難懂之處。您可以執行奇特的漸變效果以使文本淡入省略號,但我將保留該修飾性細節。
HTML結構
<!-- The block level container. `clamped-2` for 2 lines height -->
<p class="clamped clamped-2">
<!-- The inline wrapper -->
<span class="text">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat.
<!-- The ellipsis, which can contain anything you want -
(a 'more' link, for example) -->
<span class="ellipsis">
…
</span>
<!-- The fill, which covers the ellipsis when the text doesn't overflow -->
<span class="fill"></span>
</span>
</p>
的CSS
body {
/* We need a solid background or background-position: fixed */
background: #fff;
/* You'll need to know the line height to clamp on line breaks */
line-height: 1.5;
}
.clamped {
overflow: hidden;
position: relative;
}
/* Clamp to 2 lines, ie line-height x 2:
Obviously any number of these classes can be written as needed
*/
.clamped-2 {
max-height: 3em;
}
/* The ellipsis is always at the bottom right of the container,
but when the text doesn't reach the bottom right...
*/
.clamped .ellipsis {
background: #fff;
bottom: 0;
position: absolute;
right: 0;
}
/* ...It's obscured by the fill, which is positioned at the bottom right
of the text, and occupies any remaining space.
*/
.clamped .fill {
background: #fff;
height: 100%;
position: absolute;
width: 100%;
}
這是一個小提琴,用于演示它:調整瀏覽器的寬度或更改文本以查看其從省略號變為無省略號。
除了任意的優雅因素之外,我相信它比流行的解決方案性能更高,因為它不依賴浮點數(需要大量重繪)-絕對定位更容易計算,因為計算時沒有相互依賴關系布局。
- 3 回答
- 0 關注
- 740 瀏覽
相關問題推薦
添加回答
舉報