I came up with this idea. The script will measure the contents of the div, and if its width exceeds the width of the div, this will slightly reduce the content, so it can combine the char ellipsis and put the ellipsis char:
<style> div { width: 100px; height: 1em; overflow: hidden; white-space: nowrap; } </style> <div>Short text.</div> <div>Extremely long text.</div> <script> (function () { var list = document.getElementsByTagName('div'); for (var i = 0; i < list.length; i++) { var spanElement = document.createElement('span'); while (list[i].childNodes.length) spanElement.appendChild(list[i].firstChild); list[i].appendChild(spanElement); if (list[i].firstChild.offsetWidth > list[i].offsetWidth) { var ellipsisSpanElement = document.createElement('span'); ellipsisSpanElement.appendChild(document.createTextNode('β¦')); list[i].appendChild(ellipsisSpanElement); var newWidth = list[i].offsetWidth - ellipsisSpanElement.offsetWidth; list[i].firstChild.setAttribute('style', 'overflow: hidden; white-space: nowrap; display: block; float: left; width: ' + newWidth + 'px'); } } })(); </script>
I did not use YUI in this example, I almost do not know this library. I am sure that this code could be written much easier by avoiding all of these DOM methods and using YUI substitutes.
Disadvantage: the script roughly cuts the letter at the end, which doesnβt look so good. But measuring the width of the contents by letter by letter or even in a logarithmic way costs too much time. So far this is my best idea.
Decision. Use text-overflow: ellipsis in browsers that support this, and a script in others.
List of all text-overflow: ellipsis , many of them are not working yet. Successfully tested in IE 8.0, Opera, Chrome.
text-overflow: ellipsis; -o-text-overflow: ellipsis; -icab-text-overflow: ellipsis; -khtml-text-overflow: ellipsis; -moz-text-overflow: ellipsis; -webkit-text-overflow: ellipsis;
source share