此文章主要引用的是別人的,我只是把原文的jq版改爲js版,並稍微改了一點。原文地址http://www.360doc.com/content/14/0709/13/13518188_393166090.shtmljavascript
1.給DIV設置屬性:width: 200px; text-overflow: ellipsis; white-space:nowrap;overflow: hidden; 當div裏面的內容總寬度找過 200PX的時候,超出的部分會以「...」的形式顯示。html
2.上面那個案例之適用於單行文本的現實,纔會有效。但當div裏面的內容出現多行的時候則不能達到預期的效果。下面是解決多行的時候顯示「...」的方案。java
<!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>
github 預覽地址:http://htmlpreview.github.io/?https://github.com/623023808/my_cme_res/blob/master/WebSite/test/201703/heightOverflowEllipsis.htmlgit
實際應用預覽地址:傳送門github
實際應用的時候大家可能用到函數以下函數
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)(\.\.\.)?$/, "..."); } } }