需求:显示文本,最多显示三行,多余的显示 ... 展开,点击展开收起.javascript
效果以下:css
须要考虑的点:换行,展开的时候遮住收起html
若是是不须要有固定在右侧的展开收起,那么移动端直接用css3:java
overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical
以前想过用屏幕宽度减去两边留白 除以字体大小,得出每一行能够显示多少行字。css3
var oneCount = Math.floor((window.innerWidth - 55-15 ) / 16),
function getStrByteLen(v) { //一个中文按照两个字节算,返回长度 return v ? v.replace(/[\u00FF-\uFFFF]/g, " ").length : 0; }
然而须要考虑的因素不少:web
一、头部有标签,得加入计算dom
二、有换行ide
三、单行可显示的字符数不是恰好对应上,如能够显示3个字符,那么“aa中",则中字换行。字体
……spa
等等老是很难达到比较满意的效果。显示总有出入。
真正解决问题是使用
getClientRects
getClientRects这个方法若是是读取div元素上的,则老是一行
<div class="txt"> 我是一个小文本, 我是一个小文本 </div>那么以下:
document.querySelector(".txt").getClientRects()
读取到的老是一行
须要把块级元素div ---> 行内元素span
function handleTxt() { var dom = document.querySelectorAll(".quan_feed_desc[data-shareid]"); for(var i=0,len=dom.length;i<len;i++){ var shareid = dom[i].dataset.shareid; if(typeof shareid=="undefined") continue; var obj={}; for(var j=feedObj.openText,len2=feedObj.feedlist.length;j<len2;j++){//openText,记录上次计算到哪里了。 if(feedObj.feedlist[j].shareid==shareid){ obj = feedObj.feedlist[j]; break; } } var rect = dom[i].getClientRects(); var h = getLength(rect); if(h<3||!obj.showTxt){ dom[i].removeAttribute("data-shareid"); continue; } var tl=0,t = obj.showTxt; dom[i].querySelectorAll(".dot").forEach(function (el) { el.style.display="inline-block";//把点点和展开放开,为后面计算更真实 }); var showtxt = dom[i].querySelector(".showtxt"); while(h>3){ var step=1; if(/<br\/>$/.test(t)){//回退的时候,若是碰到换行要总体替换 step = 5; } t = t.slice(0,-step); showtxt.innerHTML = t; h = getLength(dom[i].getClientRects()); tl+=step; } obj.hideTxt =obj.showTxt.slice(obj.showTxt.length-tl); if(obj.hideTxt){ var height=dom[i].querySelector(".quan_feed_more").offsetWidth;//页面展开更多的大小 obj.hideTxt+=(rect[rect.length-1].width>(dom[i].offsetWidth-height)?'<span style="display:inline-block;width:'+height+'px"></span>':'');//页面收起和正文重叠 } obj.showTxt = t; obj.txtDone = 1; dom[i].removeAttribute("data-shareid"); } feedObj.openText = feedObj.feedlist.length; }
function getLength(list){ var line = 0, lastBottom=0; for(var i=0,len=list.length;i<len;i++){ if(list[i].bottom ==lastBottom){ return; } lastBottom = list[i].bottom; line++; } return line; }