What's the quickest way to truncate paragraph text that may or may not include HTML elements?

后端 未结 3 1264
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 14:14

I need to truncate paragraph text that may or may not include HTML tags. I\'m looking for the most efficient way to do this with straight jQuery or vanilla javascript. You c

3条回答
  •  时光取名叫无心
    2021-01-13 14:38

    If this is for display on a page, a neater way may be to use CSS. Given the HTML:

        this is truncated text
    

    and the CSS:

        .truncated {
            overflow: hidden;
            display: block;
            width: 50px;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    

    this will display something similar to:

        this is...
    

    You can then use JavaScript to remove the CSS class when required. Sample implementation: http://jsfiddle.net/a8QK4/

提交回复
热议问题