JS實現段落的收縮與展開
主要是使用-webkit-line-clamp這個屬性進行限制顯示行數,通過計算文字在標簽內的顯示高度來計算當前文字行數,再與需要限制的行數進行對比,來確定是否顯示
代碼如下:
1 <!--Created by lmj on 2017/8/10.-->
2
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="utf-8">
7 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
8 <title>段落的收起與展開</title>
9 <script src="js/jquery.js"></script>
10 <style type="text/css">
11 .info-shrink-text {
12 display: -webkit-box;
13 overflow: hidden;
14 text-overflow: ellipsis;
15 -webkit-box-orient: vertical;
16 }
17
18 #info-manager-content {
19 text-indent: 2em;
20 font-size: 12px;
21 color: #404040;
22 font-family: 微軟雅黑;
23 }
24
25 .more-text {
26 display: -webkit-box;
27 width: 100%;
28 -webkit-box-sizing: border-box;
29 -webkit-box-pack: end;
30 padding-right: 10px;
31 color: #00a5e0;
32 font-size: 14px;
33 }
34 </style>
35 </head>
36 <body>
37 <div class="ui-tab">
38 <P id="info-manager-content" class="info-shrink-text">
39 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 40 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 41 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 42 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 43 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 44 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 45 測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起.測試段落的展開與收起. 46 測試段落的展開與收起.測試段落</P>
47 <div class="more-text">查看更多</div>
48 </div>
49
50 <script type="text/javascript">
51 var isHide = true; 52 var textContainer; 53 function initView() { 54 textContainer = $("#info-manager-content"); 55 var single=document.createElement("div"); 56 // 設置文字樣式
57 single.style.cssText = "padding:0;visibility:hidden;font-familly:微軟雅黑;font-size:12px"; 58 single.innerHTML = "單"; 59 document.body.appendChild(single); 60 //獲取該樣式下的單個文字的高度
61 var singleHeight = single.offsetHeight; 62 document.body.removeChild(single); 63 //獲取整個段落的高度
64 var paragraphHeight = textContainer.innerHeight(); 65 //設置你要限制的高度
66 var limitHeight = 50; 67 //當前文本行數
68 var currentLine = (paragraphHeight/singleHeight).toFixed(0);
69 //轉化為行數
70 var lineCount = (limitHeight / singleHeight).toFixed(0); 71 // alert(singleHeight+"----"+paragraphHeight+"---"+lineCount+"---"+currentLine);
72 // 修改段落限制行數
73 textContainer.attr("style", "-webkit-line-clamp:" + lineCount); 74 // 設置按鈕的顯示或隱藏
75 if (currentLine >= lineCount) { 76 $(".more-text").show(); 77 isHide = true; 78 } else { 79 $(".more-text").hide(); 80 } 81 } 82 initView(); 83
84 window.onresize = function () { 85 initView(); 86 }; 87 //添加點擊事件
88 $(".more-text").on("click", function () { 89 if (isHide) { 90 textContainer.removeClass("info-shrink-text"); 91 $(this).text("收起"); 92 isHide = false; 93 } else { 94 textContainer.addClass("info-shrink-text"); 95 $(this).text("查看更多"); 96 isHide = true; 97 } 98
99 }); 100 </script>
101 </body>
102 </html>
原文地址:https://blog.csdn.net/carryworld/article/details/77258685
