ellipsifying the text in a yui datatable

◇◆丶佛笑我妖孽 提交于 2020-01-01 17:12:20

问题


hey I'm looking for a good way to ellipsify text in a yui datatable. By that I mean, formatting the text so that it fits nicely into its cell and has an ellipse (...) trailing it if the text had to be truncated.

I want to do this wihtout the use of CSS selectors, because I have a large dataset and selecting each cell by classname would be expensive.

Any good suggestions on how to do this using a formatter or something similar.


回答1:


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;


来源:https://stackoverflow.com/questions/3660052/ellipsifying-the-text-in-a-yui-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!