JavaScript 如何計算文本的行數的實現
需求:根據行數決定是否限制展開和收起。
思路:用2個塊統計行高,一個不加高度限制用來統計行數(css隱藏),一個加高度限制用來顯示(加高度限制會導致統計行數不準)
要想知道文本的行數,那就需要知道文本的總高度和每一行的高度,總高度除以行高就是行數。當然總高度的計算必須是文字所在的 DOM 沒有對高度的限制,隨著文本的增加 DOM 要隨之變高才行;最后還要考慮 DOM 的樣式padding和margin對高度的影響。這樣一來我們就可以計算出文本的行數了。總結一下我們需要如下幾步:
克隆文本所在的 DOM; 清除 DOM 的高度限制; 獲取 DOM 的行高和高度; 計算行數; 去除克隆的 DOM。相關代碼
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; } });
到此這篇關于JavaScript 如何計算文本的行數的實現的文章就介紹到這了,更多相關JavaScript 計算文本行數內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: