生活随笔
收集整理的這篇文章主要介紹了
文本溢出截断省略
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
(1)單行文本溢出省略
<style
>.demo
{white
-space
: nowrap
;overflow
: hidden
;text
-overflow
: ellipsis
;}
</style
>
<body
><div
class="demo">這是一段很長的文本
</div
>
</body
>
(2)多行文本溢出省略
多行文本溢出省略(按行數)
多適用于移動端頁面,因為移動設備瀏覽器更多是基于 WebKit 內核
<style
>.demo
{display
: -webkit
-box
;overflow
: hidden
;-webkit
-line
-clamp
: 2;-webkit
-box
-orient
: vertical
;}
</style
><body
><div
class='demo'>這是一段很長的文本
</div
>
</body
>
基于 JavaScript 的實現方案
<script type
="text/javascript">const text
= '這是一段很長的文本';const totalTextLen
= text
.length
;const formatStr = () => {const ele
= document
.getElementsByClassName('demo')[0];const lineNum
= 2;const baseWidth
= window
.getComputedStyle(ele
).width
;const baseFontSize
= window
.getComputedStyle(ele
).fontSize
;const lineWidth
= +baseWidth
.slice(0, -2);const strNum
= Math
.floor(lineWidth
/ +baseFontSize
.slice(0, -2));let content
= '';const totalStrNum
= Math
.floor(strNum
* lineNum
);const lastIndex
= totalStrNum
- totalTextLen
;if (totalTextLen
> totalStrNum
) {content
= text
.slice(0, lastIndex
- 3).concat('...');} else {content
= text
;}ele
.innerHTML
= content
;}formatStr();window
.onresize = () => {formatStr();};
</script
><body
><div
class='demo'></div
>
</body
>
總結
以上是生活随笔為你收集整理的文本溢出截断省略的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。