通过javascript实现段落的收缩与展开

主要是使用-webkit-line-clamp这个属性进行限制显示行数,通过计算文字在标签内的显示高度来计算当前文字行数,再与需要限制的行数进行对比,来确定是否显示

代码如下:

<!--Created by lmj on 2017/8/10.--> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta content="initial-scale=1, maximum-scale=1, user-scalable=no"> <title>段落的收起与展开</title> <script src="https://www.jb51.net/js/jquery.js"></script> <style type="text/css"> .info-shrink-text { display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-box-orient: vertical; } #info-manager-content { text-indent: 2em; font-size: 12px; color: #404040; font-family: 微软雅黑; } .more-text { display: -webkit-box; width: 100%; -webkit-box-sizing: border-box; -webkit-box-pack: end; padding-right: 10px; color: #00a5e0; font-size: 14px; } </style> </head> <body> <div> <P> 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起.测试段落的展开与收起. 测试段落的展开与收起.测试段落</P> <div>查看更多</div> </div> <script type="text/javascript"> var isHide = true; var textContainer; function initView() { textContainer = $("#info-manager-content"); var single=document.createElement("div"); // 设置文字样式 single.style.cssText = "padding:0;visibility:hidden;font-familly:微软雅黑;font-size:12px"; single.innerHTML = "单"; document.body.appendChild(single); //获取该样式下的单个文字的高度 var singleHeight = single.offsetHeight; document.body.removeChild(single); //获取整个段落的高度 var paragraphHeight = textContainer.innerHeight(); //设置你要限制的高度 var limitHeight = 50; //当前文本行数 var currentLine = (paragraphHeight/singleHeight).toFixed(0); //转化为行数 var lineCount = (limitHeight / singleHeight).toFixed(0); // alert(singleHeight+"----"+paragraphHeight+"---"+lineCount+"---"+currentLine); // 修改段落限制行数 textContainer.attr("style", "-webkit-line-clamp:" + lineCount); // 设置按钮的显示或隐藏 if (currentLine >= lineCount) { $(".more-text").show(); isHide = true; } else { $(".more-text").hide(); } } initView(); window.onresize = function () { initView(); }; //添加点击事件 $(".more-text").on("click", function () { if (isHide) { textContainer.removeClass("info-shrink-text"); $(this).text("收起"); isHide = false; } else { textContainer.addClass("info-shrink-text"); $(this).text("查看更多"); isHide = true; } }); </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/bc7a7a1db6ef09647782f713c3a7890d.html