简体   繁体   中英

Is there any way to know how many characters are retained or visible after text-overflow:ellipsis and overflow:hidden is applied?

I have a string of email addresses separated by a delimiter ';'and want to show all text as it is. Also want to clip any overflow text over one line and then show +count of emails ids remaining that user did not get to see(driven by some @ and; character logic). Is there any way to know how many characters are retained/ or even removed from the HTML text after the it is clipped?

I don't know what is your criteria exactly, but here is an example of how it can be calculated:

 var span = document.getElementById("text"); var countSpan = document.getElementById("count"); var orig = span.innerText; var vis = orig; while(vis.length && span.scrollWidth > parseFloat(window.getComputedStyle(span).width)) { vis = vis.slice(0,-1); span.innerText = vis + "...."; } span.innerText = orig; var visibleText = vis; var truncatedText = orig.replace(new RegExp("^" + vis.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), ""); var visibleCleanLessText; var visibleCleanMoreText; var truncatedCleanLessText; var truncatedCleanMoreText; if (truncatedText === "" || truncatedText.substr(0, 1) == ";") { visibleCleanLessText = vis; visibleCleanMoreText = vis; truncatedCleanLessText = truncatedText.substr(1); truncatedCleanMoreText = truncatedCleanLessText; } else { var m = vis.match(/;([^;]*)$/); visibleCleanLessText = m? vis.replace(/;[^;]*$/, ""): ""; visibleCleanMoreText = vis + (truncatedText.match(/^([^;]*);/) || ["",""])[1]; truncatedCleanMoreText = (m? m[1]: vis) + truncatedText; truncatedCleanLessText = truncatedText.replace(/^[^;]*;/, ""); } var truncatedCount = truncatedCleanMoreText === ""? 0: truncatedCleanMoreText.split(";").length; if (truncatedCount) { countSpan.innerText = "+" + truncatedCount; span.title = orig; } console.log("orig ", orig); console.log("visible ", vis); console.log("truncated ", truncatedText); console.log("visibleCleanLess ", visibleCleanLessText); console.log("truncatedCleanMore", truncatedCleanMoreText); console.log("visibleCleanMore ", visibleCleanMoreText); console.log("truncatedCleanLess", truncatedCleanLessText);
 div { vertical-align: middle; }.truncate { width: 300px; display: inline-block; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; }.count:empty { display: none; }.count { display: inline-block; position: relative; font-family: monospace; font-size: 90%; left: -0.5em; border: 1px solid black; border-radius: 0.3em; padding: 0.1em; }
 <div> <span id="text" class="truncate">email1@example.com;email2@example.com;email3@example.com;email4@example.com</span> <span id="count" class="count"></span> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM