3

我想确定一段文本是否被截断/显示省略号,以便我可以有条件地在[more]其后添加一个链接。

这是我正在使用的 CSS:

.more-text-collapse {
    display:inline-block;
    max-width:400px;
    height:1.2em;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}

我适用于<div>. 当里面的文本超过 400px 时,它会在末尾显示一个省略号。在那种情况下,我想添加一个[more]链接来扩展文本。

如何确定是否需要显示链接?

示例小提琴

4

2 回答 2

2

根据这个答案,这里有代码:

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

var elmW = $('.more-text').width(),
    txtW = $('.more-text').textWidth();
if(elmW < txtW) $('.more-text').after('[more]');

http://jsfiddle.net/Sergiu/EvD3J/1/

于 2013-02-08T01:02:10.517 回答
0

Looks like I can do what I want using these styles:

.more-text {
    line-height: 1.2em;
    display:none;
    white-space: nowrap;
}

.more-text-collapse {
    display:inline-block;
    max-width:400px;
    height:1.2em;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}

.more-text-expand {
    display:inline;
    white-space: pre-wrap;
}

I give each of <divs> just the more-text class which lets them spread to their full width but hides them so they don't muck up the interface, then I compute their width and override class:

$('.more-text').each(function(i,el) {
    var width = $(this).width();
    $(this).addClass('more-text-collapse');
    if(width > 400) {
        $('<a>', {href:'#',class:'more-link'}).text('[more]').insertAfter(this);
    }
});

Actually, we can take the width out of the CSS entirely so that we only have to define it in one place:

var maxWidth = 400;
$('.more-text').each(function(i,el) {
    var width = $(this).width();
    if(width > maxWidth) {
        $(this).addClass('more-text-collapse').css('max-width',maxWidth);
        $('<a>', {href:'#',class:'more-link'}).text('[more]').insertAfter(this);
    } else {
        $(this).addClass('more-text-expand');
    }
});

Would be nice if I could animate the text expanding...

于 2013-02-08T00:49:31.427 回答