需求:根據(jù)行數(shù)決定是否限制展開和收起。
思路:用2個塊統(tǒng)計行高,一個不加高度限制用來統(tǒng)計行數(shù)(css隱藏),一個加高度限制用來顯示(加高度限制會導(dǎo)致統(tǒng)計行數(shù)不準)
要想知道文本的行數(shù),那就需要知道文本的總高度和每一行的高度,總高度除以行高就是行數(shù)。當然總高度的計算必須是文字所在的 DOM 沒有對高度的限制,隨著文本的增加 DOM 要隨之變高才行;最后還要考慮 DOM 的樣式padding和margin對高度的影響。這樣一來我們就可以計算出文本的行數(shù)了。總結(jié)一下我們需要如下幾步:
- 克隆文本所在的 DOM;
- 清除 DOM 的高度限制;
- 獲取 DOM 的行高和高度;
- 計算行數(shù);
- 去除克隆的 DOM。
相關(guān)代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
document.getElementById( "noticeContent" ).innerText = str; //展示的塊 document.getElementById( "noticeContent2" ).innerText = str; //計算行高的塊 this .$nextTick(() => { let noticeDom = document.getElementById( "noticeContent2" ); console.log(noticeDom); let style = window.getComputedStyle(noticeDom, null ); let row = Math.ceil( Number(style.height.replace( "px" , "" )) / Number(style.lineHeight.replace( "px" , "" )) ); //總行高 / 每行行高 console.log( "noticeDom===>" , style.height, style.lineHeight); console.log( "rowwwww" , row); if (row > 2) { //超過2行則顯示展開和收起 this .showOmit = true ; this .showOpen = true ; } else { this .showOpen = false ; } }); |
到此這篇關(guān)于JavaScript 如何計算文本的行數(shù)的實現(xiàn)的文章就介紹到這了,更多相關(guān)JavaScript 計算文本行數(shù)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://segmentfault.com/a/1190000024445583