ellipsifying the text in a yui datatable

好久不见. 提交于 2019-12-04 16:10:23

I came up with this idea. The script will measure the content of div and if its width is above div's width, it will shrink the content a little bit, so ellipsis char could fit, and put 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 didn't use YUI in this example, I hardly know this library. I'm sure this code could be written much simpler by avoiding all of these DOM methods and using YUI's substitutes.

Disadvantage: the script roughly cuts a letter at the end, which looks not so nice. But measuring width of the content letter by letter, or even in logarithmic manner, costs too much time. For now this is my best idea.

Solution: Use text-overflow: ellipsis in browsers that support this and script in others.

List of all variants of text-overflow: ellipsis, many of these are not working yet. Tested with success 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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!