How do I determine if truncation is being applied in my style through JS?

亡梦爱人 提交于 2019-12-10 17:16:20

问题


I am applying truncation using CSS styles:

.yui-skin-sam td:not(.yui-dt-editable) .yui-dt-liner{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -ms-text-overflow: ellipsis;        
    -o-text-overflow: ellipsis;
    -moz-binding: url('ellipsis.xml#ellipsis');     
}

.yui-skin-sam td[class~=yui-dt-editable] .yui-dt-liner{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -ms-text-overflow: ellipsis;        
    -o-text-overflow: ellipsis;
}

(Sidenote: I'm not sure if this is the best way to write my CSS. This is a Firefox specific workaround since truncation on Firefox only sort-of works).

I want a tool-tip to appear over text that is truncated. How do I detect if text is truncated so that I can display a tool-tip?


回答1:


Keep in mind that CSS never alter the DOM!!!

jQuery Snippets:

$(function() {
    $('a.link').each(function(e) {
        var link = $(this).text();
        if ( link.length > 100) {
            $(this).attr('title', link );
        }
    });
});

Assuming you have links

<a class="link" href="" >the brown fox jumps over the lazy dog</a>

the above code wil produce

    <a class="link" href="" title="the brown fox jumps over the lazy dog" >
     the brown fox jumps over the lazy dog
    </a>

the text-overflow: ellipsis; property will do the rest as you know!


GOING AHEAD:

there is a small plugin here

I wanted to be able to use this feature in all browsers, so I wrote a small jQuery plugin in order to support Firefox. To use, just call ellipsis() on a jQuery object. For example:

$("span").ellipsis();
  • http://ajaxian.com/archives/text-overflow-for-firefox-via-jquery



回答2:


The question is old and was answered.

However to apply the solution given by @aSeptik you need to know in advance how many characters fits into the container, or to use a jQuery plugin.

I arrived to the same issue, and today the solution is very simple: use the clientWith and scrollWidth properties.

The content is truncated if elem.scrollWidth > elem.clientWidth.

Here is the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollWidth

And a example in jsFiddle: http://jsfiddle.net/diegof79/de9xsn4b/



来源:https://stackoverflow.com/questions/2935483/how-do-i-determine-if-truncation-is-being-applied-in-my-style-through-js

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