js容器高度溢出省略号显示
此文章主要引用的是别人的,我只是把原文的jq版改成js版,并稍微改了一点。原文地址http://www.360doc.com/content/14/0709/13/13518188_393166090.shtml
1.给DIV设置属性:width: 200px; text-overflow: ellipsis; white-space:nowrap;overflow: hidden; 当div里面的内容总宽度找过 200PX的时候,超出的部分会以“...”的形式显示。
2.上面那个案例之适用于单行文本的现实,才会有效。但当div里面的内容出现多行的时候则不能达到预期的效果。下面是解决多行的时候显示“...”的方案。
<!DOCTYPE > <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> function heightOverflowEllipsis() { var p = document.getElementById("p"); while (p.offsetHeight > document.getElementById("figcaption").offsetHeight) { p.innerText = p.innerText.replace(/(\s)*([a-zA-Z0-9]+|\W)(\.\.\.)?$/, "..."); }; } </script> <style> .figcaption { background: #EEE; width: 410px; height: 3em; margin: 1em; border:1px dashed red; } .figcaption p { margin: 0; line-height: 1.5em; } </style> </head> <body> <input type="button" value="设置高度溢出省略号" onclick="heightOverflowEllipsis()" /> <div id="figcaption" class="figcaption"> <p id="p"> You probably can't do it (currently?) without a fixed-width font like Courier. With a fixed-width font every letter occupies the same horizontal space, so you could probably count the letters and multiply the result with the current font size in ems or exs. Then you would just have to test how many letters fit on one line, and then break it up. </p> </div> </body> </html>
实际应用预览地址:传送门
实际应用的时候你们可能用到函数如下
function placeIntroductionHeightFormat() { var currentDiv, introDivs = document.querySelectorAll("#div_list .div_list_item .div_content"); for (var i = 0; i < introDivs.length; i++) { currentDiv = introDivs[i]; while (currentDiv.offsetHeight > 60) { currentDiv.innerText = currentDiv.innerText.replace(/(\s)*([a-zA-Z0-9]+|\W)(\.\.\.)?$/, "..."); } } }